Reputation: 976
I am doing a program that creates boxes when I click a button. I have a "model" box hidden so when I click the button, it clones the model box and changes its id.
Inside this boxes I have a link that have to do some function when clicked, but jQuery seems unable to find this element, so I get nothing when I click the link.
Here's my code:
$('#box-' + number).find('a').click(function(){
alert('boop'); //function
});
Variable 'number' is the number of the box. As I said the ID is changed when I clone the model box.
The model box is something like this:
<div id="box-model">
<div class="box">
<div class="heading">
<a class="link-class">¡Click Me!</a>
</div>
<div class="body">
CONTENT
</div>
</div>
</div>
Upvotes: 0
Views: 1983
Reputation: 82241
You need to use event delegation for attaching events to dynamically added element.
As the ids are generated dynamically, you can not use them as selector in event delegation. you can rether use class selector to target anchor elements inside .header
:
$('body').on('click','.heading a',function(){
alert('boop'); //function
});
Upvotes: 3
Reputation: 227
$("body").find('#box-' + number).find('a').click(function(){
alert('boop'); //function
});
The thing is, jQuery has loaded DOM before the box is generated. Assuming this code is in your $(document).ready(function()), your boxes are not yet generated when the document is ready. You need to go to "#box"'s parent element that was generated at the start (it doesnt have to be body)
Upvotes: -1