2

Markup:

<ul>
<li><a href="#" class="item-list" data-id="1">Link 1</a></li>
<li><a href="#" class="item-list" data-id="2">Link 2</a></li>
<li><a href="#" class="item-list" data-id="3">Link 3</a></li>
</ul>

In JQuery, i would select link 1 and it should be able to fetch the data-id of link1. I tried

$('.item-list').click(function(){
 var link = $(this);
 alert($(this).data('id'));
});

It doesn't have any result.

Oh. the list gets generated after the page is loaded. I am querying the DB to get the list. Also, it is also possible for the list to change, depending on how the user filters the dB.

Thanks.

0

3 Answers 3

4

If the list is generated after the page is loaded, the .click binding might not work. Maybe you can try .live, like so:

$('.item-list').live('click', function(){
   var link = $(this);
   alert($(this).data('id'));
});

EDIT:

What I always seem to forget :) as of jQuery 1.7, .live() is deprecated. You should use .on() like so:

 $("body").on("click",".item-list",function(){
    var link = $(this);
    alert($(this).data('id'));
});
Sign up to request clarification or add additional context in comments.

3 Comments

since jquery 1.7 .live() is deprecated. Use .on() instead.
dude this is wrong way of using on if the content is loaded after attaching event to DOM
I had an error in my .on() example, as @Somebodyisintrouble correctly mentioned. I edited the example. You can also look at his answer!
2

use .on because live is deprecated and also put your code inside document.ready()

$(function(){  //short form of document.ready        
    $("body").on("click",".item-list",function(){
        var link = $(this);
        alert($(this).data('id'));
    });
});

2 Comments

My example isn't exactly what my data is structured. What if it was .item-list is in a table?
No problem until .item-list is inside body
0
$('ul').on('click', '.item-list', function() {
  var link = $(this);
  alert(link.attr('data-id'));
});

See if that works

1 Comment

Wouldn't it be link.attr('data-id') then?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.