Search code examples
jquery

Can't get ID of clicked link


Maybe I'm being crazy, but I can't get the ID of the <a> link that is being clicked. The var for security works fine, and there is definitely content in the ID attribute. Am I missing something?

Here is the PHP -

<span id="<?php echo $load_post_content_nonce; ?>">
    <a href="<?php the_permalink(); ?>" id="<?php the_ID(); ?>" class="read-more" target="_blank">Read more...</a>
</span>

Here is the JS -

$(document).ready(function(){   

    $('a.read-more').live('click', function(e){

        e.preventDefault();

        var id = $(this).attr('id');
        var security = $(this).parent('span').attr('id');

    });
    
});

Here is the HTML output from one of the links -

<span id="b494a85e81">
    <a id="6623" class="read-more" href="http://test.dynedrewett.com/warring-parents-told-to-face-up-not-fall-out-over-contact-with-children/">Read more...</a>
</span>

Solution

  • As others have pointed out, .live() is deprecated as of jQuery 1.7. Even in older versions, .delegate() is now the preferred method for handling delegated events. For later versions, on() is the correct method for handling delegated events, as explained in the jQuery docs for .live() which explains how to port to .on().

    This does work for content generated dynamically after DOM ready with AJAX or some other method, but you have to use the correct syntax. For handling clicks on dynamically generated .read-more links, do the following:

    $(document).ready(function(){
    
        $(document).on('click', 'a.read-more', function(e) {
            e.preventDefault();
    
            var id = this.id;
            var security = $(this).parent('span').attr('id');
        });
    });
    

    In $(document).on('click', 'a.read-more', function(e) {...}), you can replace document with any static parent element (one which exists at the time the handler is bound, and which is guaranteed to exist 'forever', in order to handle clicks on future .read-more links; the documentation explains the usage in depth.

    As of the time of this writing, the jQuery object does not have a property named id; to access an element's ID you must either:
    - Use .attr( 'id' )
    or
    - Use the native DOM element's id property: $(element)[0].id or element.id