Skip to content Skip to sidebar Skip to footer

Onclick Get "id" Attribute Of "a" Tag

I have list view in jQuery Mobile web app this list view is made of elements like this:
  • Solution 1:

    The first problem you've got is duplicate search_r id attributes, which is invalid. These should be changed to classes. Also, you should be using on() with a delegate handler, as live() has been removed from the latest version of jQuery. Try this:

    <liclass='search_r'><ahref='#'id='$id'class='s_result'></a></li><liclass='search_r'><ahref='#'id='$id'class='s_result'></a></li>
    $("#cc_page").on('click', '.search_r', function(){
        var search_r = $('a', this).attr('id');
        console.log(search_r); // just to check it works// I assume this is just for testing, otherwise leaving the page // immediately on click renders getting the id completely moot.//window.location.href = "http://imes.********.com/app/userpanel.html#sfpp_page";
    });
    

    I also assume the $id in your HTML is from some form of templating engine which gets interpreted? If not, those will also need to be made unique.

    Solution 2:

    window.location.href causes the browser to make a new request. Any variables will be reset when the new page loads.

    What is your goal with search_r?

    Solution 3:

    .live has been deprecated in jQuery since v1.7, and has been removed in v1.9.

    You should replace it with .on().

    .on has 2 syntaxes for binding elements, whereas .live only had 1.

    If the element exists at the time you are binding, you do it like this:

    $('.element').on('click', function(){
        .......
    });
    

    You can even use the shorthand:

    $('.element').click(function(){
        .........
    });
    

    If the element does not exist at the time, or new ones will be added (which is what .live was normally used for), you need to use "event delegation":

    $(document).on('click', '.element', function(){
        .............
    });
    

    NOTE: You want to bind to the closest static element, not always document.

    In the meantime, the jQuery Migrate plugin can be used to restore the .live() functionality if you upgrade your jQuery to the newest version.

  • Post a Comment for "Onclick Get "id" Attribute Of "a" Tag"