This question already has an answer here:
(这个问题已经在这里有了答案:)
Suppose I have some jQuery code that attaches an event handler to all elements with class .myclass
.
(假设我有一些jQuery代码,将事件处理程序附加到所有类为.myclass
元素上。)
For example:
(例如:)
$(function(){
$(".myclass").click( function() {
// do something
});
});
And my HTML might be as follows:
(我的HTML可能如下所示:)
<a class="myclass" href="#">test1</a>
<a class="myclass" href="#">test2</a>
<a class="myclass" href="#">test3</a>
That works with no problem.
(没问题。)
However, consider if the .myclass
elements were written to the page at some future time.(但是,请考虑是否在将来某个时间将.myclass
元素写入页面。)
For example:
(例如:)
<a id="anchor1" href="#">create link dynamically</a>
<script type="text/javascript">
$(function(){
$("#anchor1").click( function() {
$("#anchor1").append('<a class="myclass" href="#">test4</a>');
});
});
</script>
In this case, the test4
link is created when a user clicks on a#anchor1
.
(在这种情况下,当用户单击a#anchor1
时将创建test4
链接。)
The test4
link does not have the click()
handler associated with it, even though it has class="myclass"
.
(尽管test4
链接具有class="myclass"
,但它没有与click()
处理函数关联的内容。)
Basically, I would like to write the click()
handler once and have it apply to both content present at page load, and content brought in later via AJAX / DHTML .
(基本上,我想编写一次click()
处理函数,并将其应用于页面加载时出现的内容以及以后通过AJAX / DHTML引入的内容。)
Any idea how I can fix this?(知道我该如何解决吗?)
ask by frankadelic translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…