I am using JQuery Ajax to grab data. I want to have all anchor tags in my code that if somebody clicks on a tag, it doesn't fire and call Ajax instead. The following is my code, but it does not work.
$('.one_item a').each(function(){
$(this).live('click', function(){
alert($(this).attr('href'));
return false;
});
});
I am using JQuery version 1.5, so .live should work. Any ideas? Cheers.
.live
has to be applied to the selector. When you use .each()
, you don't get the benefit of handling events on elements added dynamically, because you're just iterating over the elements found at the time the loop was run.
$('.one_item a').live('click', function(){
alert($(this).attr('href'));
return false;
});
You can use .live()
directly on the selector:
$('.one_item a').live('click', function(e) {
e.preventDefault();
alert($(this).attr('href'));
});
It should work, see this demo .
However, it keeps iterating
alert($(this).attr('href'));
. How can I make it fire only on the items I clicked?
Make sure you are not triggering the click()
event loop somewhere else, such as:
$('.one_item a').each(function() {
$(this).click();
// other stuff
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.