jQuery函数不绑定到新添加的dom元素 [英] jQuery function not binding to newly added dom elements
本文介绍了jQuery函数不绑定到新添加的dom元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是 index.html
:
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.btn_test').click(function() { alert('test'); });
});
function add(){
$('body').append('<a href=\'javascript:;\' class=\'btn_test\'>test</a>');
}
</script>
</head>
<body>
<a href="javascript:;" class="btn_test">test1</a>
<a href="javascript:;" onclick="add()">add</a>
</body>
如果我点击 test1
链接,显示 alert('test')
,但如果我点击添加
链接,请点击测试
,它没有显示任何内容。
If I click on test1
link, it shows alert('test')
, but if I click on add
link then click on test
, it doesn't show anything.
你能解释一下吗?
推荐答案
对于2011年之后提出此问题的用户,有一种新的正确方法:
For users coming to this question after 2011, there is a new proper way to do this:
$(document).on('click', '.btn_test', function() { alert('test'); });
这是从jQuery 1.7开始。
This is as of jQuery 1.7.
有关详细信息,请参阅直接和委派活动
For more information, see Direct and delegated events
这篇关于jQuery函数不绑定到新添加的dom元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文