Dean219 Dean219 - 1 year ago 76
jQuery Question

dynamic <a href> event without replacing

Hey im having a problem creating a dynamic ahref event. The problem is that i dont want it to perform the default event of just linking. So i have blocked the default and want to replace content inside a div like so, here is the working code:

echo '<a href="/mydirectory/index.php?id=',$id,'">';
echo '<script>
$( "a" ).click(function( event ) {
echo '}); </script>';

This works perfectly as i expeted, the problem is that by using this:

$( "a" ).click(function( event ) {

It sets all elements of 'a' on the page to link to the last link clicked. However using a unique ID on the href seems to redirect just directly to the html rather than replacing the content and there are no errors when i checked on chrome:

<a href="/mydirectory/index.php?id=',$id,'" id="mylink">
$( "#mylink" ).click(function( event ) {

So my question is simply, how do i retain the functionality that seems to work for some reason only on the a href and stop it replacing all the a-hrefs elsewhere in the site with the same function?

Answer Source

I don't know how many link and how you generated anyway you can use 'click' function and get the attr href than use it how you like. Than over preventDefault use event.stopImmediatePropagation() look the code if you have any question let me know

<a href="/mydirectory/index.php?id=',$id,'" id="mylink">click me</a>

$('a#mylink').click(function(event) {
    var link_url = $(this).attr('href');


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download