Click事件不适用于动态添加的按钮

编程入门 行业动态 更新时间:2024-10-21 16:23:42
本文介绍了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?

注意:由于绑定到嵌套在Dom中的多个视图模型

更新的引用

  • 使用jQuery on()取消click事件不会通过Ajax调用在注入的HTML上触发
  • 如何为新注入的注入附加jquery事件处理程序html?
  • >注入html之后通过jQuery,事件处理程序无法使用/不使用委托
  • 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="code.jquery/jquery-1.9.1.min.js"></script> <script src="cdn.kendostatic/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())

    来源: api.jquery/on/

    更多推荐

    Click事件不适用于动态添加的按钮

    本文发布于:2023-11-23 14:04:01,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1621700.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:按钮   不适用于   事件   动态   Click

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!