Click事件不适用于动态添加的按钮 [英] Click event is not working for dynamically added button

查看:84
本文介绍了Click事件不适用于动态添加的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我拒绝了在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?

注意:由于 更新的引用

  1. 使用jQuery on()取消click事件不会通过Ajax调用在注入的HTML上触发
  2. 如何为新注入的注入附加jquery事件处理程序html?
  1. Wiring up click event using jQuery on() doesn't fire on injected HTML via Ajax call
  2. how to attach jquery event handlers for newly injected html?
  3. 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:

jsFiddle演示

$(".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())

来源: http://api.jquery.com/on/

这篇关于Click事件不适用于动态添加的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆