jQuery不选择元素 [英] jQuery not selecting element
问题描述
我正在做一个程序,当我单击一个按钮时会创建一个盒子.我隐藏了一个模型"框,因此当我单击按钮时,它会克隆模型框并更改其ID.
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.
在此框中,我有一个链接,当单击该链接时,它必须执行某些功能,但是jQuery似乎找不到该元素,因此,当我单击该链接时,我什么也没得到.
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.
这是我的代码:
$('#box-' + number).find('a').click(function(){
alert('boop'); //function
});
变量数字"是盒子的数字.正如我说的那样,克隆模型框时ID会更改.
Variable 'number' is the number of the box. As I said the ID is changed when I clone the model box.
模型框是这样的:
<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>
推荐答案
您需要使用事件委托将事件附加到动态添加的元素上.
You need to use event delegation for attaching events to dynamically added element.
由于id是动态生成的,因此不能在事件委托中将它们用作选择器.您可以使用类选择器来定位.header
中的锚元素:
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
});
这篇关于jQuery不选择元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!