jQuery .html() 中的事件不会检测到

Event in jQuery .html() won't detect

我正在尝试使用由 .html() 打印的按钮。我在搜索该站点后尝试了 .find(),但似乎仍未检测到 onclick 事件。

<div id = "div4html">div</div>
<button id="printbtn">printbtn</button>

<script>
$("#printbtn").on( "click", function() {
    $("#div4html").html('<button id ="btntest">btntest</button>');
});

$("#div4html").find("#btntest").on( "click", function() { 
    alert("on click");
});
</script>

虽然#btntest onclick 没有显示警报,但#btntest 上的CSS 有效。 关于动态创建的元素,有什么我不知道的吗?

从正文中委托事件

$("body").on( "click",'#btntest', function() { 
   alert("on click");
});

你需要做的:-$("#div4html").on( "click", "#btntest", function() {

叫做:- Event Delegation

示例:-

$("#printbtn").on( "click", function() {
  $("#div4html").html('<button id ="btntest">btntest</button>');
});

$("#div4html").on( "click","#btntest", function() { 
  alert("on click");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "div4html">div</div><br>
<button id="printbtn">printbtn</button>

你不能这样做,因为默认情况下,js 甚至不会为新创建的内容中的事件。

方法如下:

$("#div4html").on('click', "#btntest" , function() {
// Your code
}