以下是我的代码。在div中附加按钮后,附加的按钮click事件不起作用。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<button class='btn-append'>Append Buttons</button><br><br>
<div id='div-buttons'> </div>
<script>
$(document).ready(function(){
$('.btn-append').click(function(){
var content = "<button class='btn'>Button-1</button><br><br><button class='btn'>Button-2</button>";
$('#div-buttons').append(content);
})
});
$(document).ready(function(){
$(".btn").click(function(){
$(this).hide();
});
})
</script>
</body>
</html>
答案 0 :(得分:1)
您需要在页面加载时绑定事件,因为该元素不存在,因此未绑定事件。
$(document).ready(function(){
$('.btn-append').click(function(){
var content = "<button onclick='hideButton(this)'>Button-1</button><br><br><button class='btn'>Button-2</button>";
$('#div-buttons').append(content);
$(".btn").unbind();
bindBtnClass();
});
});
function bindBtnClass(){
$(".btn").bind('click', function(){
$(this).hide();
});
}
function hideButton(elem){
$(elem).hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='btn-append'>Append Buttons</button><br><br>
<div id='div-buttons'> </div>
干杯.. !!
此外,您可以直接使用按钮1中完成的实现。