Reputation: 1119
I have the following scenario; in my js I have a dynamic hyperlink that I need to capture the clicked link id.
for (var i = 0; i < neighbor.data[3].length; i++){
<a class="Chris" name="a" id="+i+" href="Chris">Hi</a>
}
Now I can get this with;
parseInt($(this).attr("ID"));
I am using this to capture the it;
$(document).on("click", "a.a", function(event) {
event.stopPropagation();
alert(clickedID);
clickedID = parseInt($(this).attr("ID"));
});
Now, my problem is that everytime I click on the hyperlink instead of only one clickedID I have one for every hyperlink clicked. Is there a way to prevent this?
Upvotes: 1
Views: 8048
Reputation: 146201
You may try this, "a.a"
should be "a.Chris"
because Chris
is the class name you have used not a
andid
should start with a non-numeric character.
for (var i = 0; i < neighbor.data[3].length; i++){
var a='<a class="Chris" name="a" id="id_'+i+'" href="Chris">Hi</a>';
$('#links').append(a);
}
$("#links").on("click", "a.Chris", function(event) { // You can use $(document).on(...) instead of $("#links").on(...)
event.preventDefault();
event.stopPropagation();
clickedID = parseInt($(this).attr("id").split('_')[1]);
alert(clickedID);
});
DEMO.
Upvotes: 0
Reputation: 15111
You have an error in your for loop. Your id="+i+"
will just set all anchor tags' IDs to +i+
because you are not escaping the plus sign and the variable i
Upvotes: 1
Reputation: 6051
I believe you are getting every anchor tag because you are setting the event on the document, rather than the anchor tag. Try this instead:
$('a').on('click',function(event) {
event.stopPropagation();
clickedID = parseInt($(this).attr('id'));
alert(clickedID);
});
Upvotes: 2