[英]Angular 8 - Dynamically added button.Click event not working
[英]Click event is not working for dynamically added button
我提到在jQuery中创建一个div元素并使用javascript 创建一个div元素 。 但是,当我动态添加按钮元素时,单击不起作用。 我们需要做些什么改变才能使按钮点击工作?
注意:由于绑定到嵌套在Dom中的多个视图模型中提到的kendo控制要求,我们无法将该函数移动到document.ready之外
更新的参考文献
码
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://cdn.kendostatic.com/2013.2.716/js/kendo.all.min.js"></script>
<script type="text/javascript">
//lijo
$(document).ready(function ()
{
$(".statiscDIV").append('<div>FIRST</div>');
$(".statiscDIV").append('<div>hello <button class="MakeHoldDetailLinkButton" onclick = "showMakeAndHold();">View</button> </div>');
//lijo
function showMakeAndHold()
{
alert("HIIIIIII");
}
});
</script>
</head>
<body>
<div class="statiscDIV">
A
</div>
</body>
将代码注入DOM时,jQuery事件处理程序不会附加/绑定到新元素。 (在注入新代码之前,jQuery已经对DOM元素进行了绑定)。 因此,当您单击按钮时,不会捕获jQuery单击事件。
要附加事件处理程序(从而从中获取事件)注入的元素,必须使用jQuery .on()
,如下所示:
$(".statiscDIV").append('<div>FIRST</div>');
$(".statiscDIV").append('<div>hello <button class="MakeHoldDetailLinkButton">View</button> </div>');
$(document).on('click','.MakeHoldDetailLinkButton',function(){
showMakeAndHold();
});
function showMakeAndHold() {
alert("HIIIIIII");
}
在jQuery 1.7中添加了.on()
方法来替换bind()
.delegate()
和.live()
- 它与所有这些相同。 (要取消绑定任何DOM元素的事件处理程序,请使用.off()
)
资料来源: http : //api.jquery.com/on/
您必须使用\\
来转义引号,或混合单引号和双引号:
"<div>hello <button class=\"MakeHoldDetailLinkButton\" onclick=\"showMakeAndHold();\">View</button> </div>"
'<div>hello <button class=\'MakeHoldDetailLinkButton\' onclick=\'showMakeAndHold();\'>View</button> </div>'
'<div>hello <button class="MakeHoldDetailLinkButton" onclick="showMakeAndHold();">View</button> </div>'
"<div>hello <button class='MakeHoldDetailLinkButton' onclick='showMakeAndHold();'>View</button> </div>"
另一个问题是您使用内联事件侦听器。 那些在全局上下文中运行,因此无法运行在闭包内声明的函数。
要么使showMakeAndHold
成为全局函数,要么以更好的方式更好地添加事件侦听器:
$(".statiscDIV")
.append('<div>FIRST</div>')
.append('<div>hello <button class="MakeHoldDetailLinkButton">View</button></div>')
.find('button').on('click', showMakeAndHold);
$(document).ready(function (){
$(".statiscDIV").append('<div>FIRST</div>');
$(".statiscDIV").append('<div>hello <button class="MakeHoldDetailLinkButton" onclick = "showMakeAndHold();">View</button> </div>');
});
//lijo
function showMakeAndHold(){
alert("HIIIIIII");
}
虽然很晚,但未来可能对某人有所帮助。
当动态添加元素/类/ Id时,您还需要添加事件侦听器。 同样,如果删除它,则也会删除附加到它的事件侦听器。
因此,要么添加事件侦听器还加入了新的元素(这不会是一个好方法),或使用jQuery的时候on
方法如下所示:
$(document).on('click','class or id', function);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.