开发者

How to get a value of element that was added with ajax in a "live" event?

Here's the thing - a click event adds a bunch of elements on the page, and they all have the same id (is there something wrong here?).

I use a live function to assign click event to all of these elements:

$("#tag").live('click', function() { console.log($("#tag").html()); });

When I click on any of them, only the value of first element gets logged.

How can I let the click event know on which of this elements I actually click? 开发者_如何学CThanks a lot!

Update: using classes and $(this) is the way to go. Problem solved. Thanks griegs and John!


If the added elements really do all have the same ID, and not the same class, then this is a problem. You'll need to post the code that's adding the elements if you'd like help with that.

I can see from the code you posted that you're attaching the live method to the .tag class, but inside the function you're referring to an element with ID #tag instead. You might want to read up on the difference between classes and IDs.

Try this, to solve your problem:

$(".tag").live('click', function() { 
    console.log($(this).html()); 
});

Alternatively, you can do the following to get the clicked-on element:

$(".tag").live('click', function(event) { 
    console.log($(event.target).html()); 
});


try using $(this).val() or $(this).html()

edit

If you want to loop through all thr #tag elements then you can still use $(this) to check the clicked tag against the element you are looping through. If that makes sense.

btw: why do you have multiple elements with the same ID? That's kinda bad. A better way might be to have elements with common class names that you can reference and attach events to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜