追加时不能访问jQuery

Cannot access jQuery when appending

本文关键字:jQuery 访问 不能 追加      更新时间:2023-09-26

我通过jQuery添加了一个按钮。

$('#toAppend').html('<input type="button" id="helloWorld">');

在我的浏览器中,我可以看到按钮,但我不能通过jQuery访问它。

代码:

$('#helloWorld').click(function () {
    alert("you clicked me");
})

任何帮助都是感激的。

谢谢。

使用on()作为事件委托:

$(document).on('click', '#helloWorld', function () {
  alert("you clicked me");
})

您必须以不同的方式访问它,因为它是在页面加载后添加到html中的:

$("#toAppend").on("click", "button#helloWorld", function(e) {
    console.log("clicked!");
});