Reputation: 15925
I have the following which seems to produce the correct html when viewed with Google Chrome's web developer tools:
$("<a />", {
text: "link text goes here"
}).attr({
href: "#",
class: "some_class_name",
id: "divSlot-" + data.id
}).appendTo("#divSlots");
I am trying to add a click event to the tags:
$(".some_class_name").on("click", function(event) {
event.preventDefault();
alert("hello");
});
When I click on the links in a browser, nothing happens, not even errors.
What have I done wrong or missed out?
Upvotes: 0
Views: 652
Reputation: 2725
try following (i just changed data.id and it works fine)
$("<a />", {
text: "link text goes here"
}).attr({
href: "#",
class: "some_class_name",
id: "divSlot-21"
}).appendTo("#divSlots");
$(".some_class_name").on("click", function(event) {
event.preventDefault();
alert("hello");
});
working example here: http://jsfiddle.net/SF6pN/
hope it helps.
Upvotes: 0
Reputation: 756
Have you tried wrapping it up in the$(document).ready(function(){/*code here*/})
?
have a look: http://jsfiddle.net/REFh5/
Upvotes: 0
Reputation: 17366
Use event delegation
$("document").on("click",".some_class_name", function(event) {
event.preventDefault();
alert("hello");
});
Upvotes: 0
Reputation: 5217
Could you add the html output it produces?
At first look nothing seems wrong. You could change your code more efficiently to:
$(".some_class_name").click(function(event) {
event.preventDefault();
alert("hello");
});
Upvotes: 0
Reputation: 388316
You need to use event delegation based event registration since you are dealing with dynamically added elements.
The .on(), you used is only a short hand for $(".some_class_name").click(...)
, to make use of event delegation you need to use a different syntax of .on()
$(document).on("click", ".some_class_name", function(event) {
event.preventDefault();
alert("hello");
});
Upvotes: 4