Click事件不适用于动态添加的按钮 [英] Click event is not working for dynamically added button
问题描述
我拒绝了在jQuery中创建div元素,并创建了一个div元素使用javascript.但是,当我动态添加按钮元素时,单击不起作用.我们需要做些什么更改才能使按钮单击工作?
I reffered Creating a div element in jQuery and creatd a div element using javascript. However when I added a button element dynamically, click is not working. What change do we need to do to make the button click working?
注意:由于 更新的引用
- Wiring up click event using jQuery on() doesn't fire on injected HTML via Ajax call
- how to attach jquery event handlers for newly injected html?
- After injecting html by jquery, the event handlers doesn't work with/without delegate
代码
<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 click事件.
When you inject code into the DOM, the jQuery event handlers are not attached/bound to the new elements. (jQuery already did the bindings to DOM elements before the new code was injected). Therefore, when you click a button, no jQuery click event is trapped.
要附加事件处理程序(从而从中获取事件),必须使用jQuery .on()
,如下所示:
To attach event handlers (and thereby grab events from) injected elements, you must use jQuery .on()
, as follows:
$(".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()
)
The .on()
method was added in jQuery 1.7 to replace bind()
, .delegate()
, and .live()
-- it does the same thing as all of these. (To unbind event handlers from ANY DOM elements, use .off()
)
这篇关于Click事件不适用于动态添加的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!