如何为将通过AJAX加载的元素声明事件处理程序

How to declare event handler for an element which will be loaded via AJAX?

本文关键字:元素 声明 事件处理 程序 加载 AJAX      更新时间:2024-04-13

我有一个按钮,点击后使用AJAX <input>加载。在我连接到页面的JS中有一个事件处理程序。我试图在同一个JS中声明<input>的事件处理程序,但它们似乎不起作用。

HTML

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="script2.js"></script>
<button>load</button>

JS-

$('button').click(function () {
    $.ajax({
        url: 'additional.html',
        context: document.body,
    }).done(function(html) {
        $('body').append(html);
    })
});
$('input').click(function () {
    alert('aasd');
});

我已经制作了测试页面,但只有在将JS插入Chrome的Web控制台后,一切才正常(由于未知原因,<head>中连接的脚本不起作用)

您应该在您的案例中使用事件委派.on。请阅读此处以获取关于.on 的完整参考

试试这个,

$(document).on('click','input',function () {
    alert('aasd');
});

使用以下代码:

<script type="text/javascript">
$(document).ready(function(){ 
$('#cl').click(function () {
$.ajax({
    url: 'additional.html',
    context: document.body,
}).done(function(html) {
    $('body').append(html);
})
});
});
$(document).ready(function(){   
$('#cl').click(function () {
alert('aasd');
});
});
</script>
<button id="cl">load</button>