动态添加的HTML不被jQuery识别 [英] Dynamically added HTML not being recognized by jQuery
问题描述
在这里阅读其他一些内容:这个类似的问题,但我不确定如何将此应用于我的困境。
Read some other things on here re: this similar problem but am not sure how to apply this to my dilemma.
我有一个jquery函数替换了一些HTML在列表中..
例如,在函数运行之前:
I have a jquery function that replaces some HTML in a list.. For example, before the function runs:
<ul id="mylist">
<li id="item1">blah blah blah</li>
<li id="item2">blah blah blah</li>
<li id="item3">blah blah blah</li>
</ul>
然后我有另一个点击LI运行,例如:
Then I have another which runs on click of the LI e.g:
$("#mylist li").click(function () {
alert($(this).attr("id"));
});
工作正常,直到我动态修改警告为空白的#mylist html。
Works fine until I dynamically modify the #mylist html, where the alert is blank.
如何替换#mylist html并仍然可以选择里面的li?
How can I replace the #mylist html and still be able to select the li's found within?
推荐答案
要在所有未来动态添加的列表项上维护此功能,您应该使用带有 $。on()的事件委派
:
To maintain this functionality on all future dynamically-added list items, you should use event delegation with $.on()
:
$("#mylist").on("click", "li", function(){
alert( this.id );
});
了解更多关于 $。on()
,在线访问 http://api.jquery.com/on/ 。
Read more about $.on()
, online at http://api.jquery.com/on/.
这篇关于动态添加的HTML不被jQuery识别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!