我附加了一个新元素,但是当我单击它时没有任何响应。
的HTML
<button>add element</button>
<div></div>
Java脚本
$(function(){
$('button').click(function(){
$('div').append('<span class="x">x</span>');
});
$('.x').click(function(){
alert('fire');
});
});
最佳答案
$(function() {
$('button').click(function() {
$('div').append('<span class="x">x</span>');
});
$('div').on('click', '.x', function() {
alert('fire');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>add element</button>
<div></div>
事件处理程序仅绑定(bind)到当前选定的元素;它们必须在您的代码进行事件绑定(bind)调用时在页面上存在。
在创建元素时。
您需要使用Event Delegation。您必须使用委托(delegate)事件方法使用.on()。
一般语法
$(document).on(event, selector, eventHandler);
理想情况下,应使用最接近的静态容器替换
document
。例
$('div').on('click', '.x', function(){
alert('fire');
});