【问题标题】:Jquery event not firing for a button created in javascript with innerHTML [duplicate]Jquery事件未触发在javascript中使用innerHTML创建的按钮[重复]
【发布时间】:2015-02-03 16:18:27
【问题描述】:

我在网上搜索但无法完成这项工作..

我正在 js.file 中创建一个对话框。在这个 js 中,我有一个创建按钮的函数,但使用的是 innerHTML...

    var divButtons = document.getElementById('buttons_insert1');    
    var buttons_insert = "<button id='okcad' class='button_ok' value='' > <img src='/php/Images/OK.png' alt='OK' /> OK </button>";
    divButtons.innerHTML = divButtons.innerHTML + buttons_insert;

在 index.html 中我有一个 jquery 函数来获取点击事件。

$("#okcad1").click(function() 
{
   alert('hello world');
}

但这不起作用..事件不会触发...

有人可以帮助我吗?

问候!

拉斐尔 S.

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    使用event delegation

    $(document).on("click" , "#buttons_insert1 #okcad1" , function() 
    {
       alert('hello world');
    });
    

    【讨论】:

    • @downvoters 关心评论
    • 感谢 Amit 和 JqueryKing!但只有 JQueryKing 的答案有效……你能告诉我为什么吗?谢谢!
    • 谢谢。我使用了等效的 javascript,它运行良好。 Rafael,我怀疑 Amit 的回答是将事件分配给错误的元素。
    【解决方案2】:

    您需要事件委托,因为您是在加载 DOM 之后附加它。为此使用jQuery.on

    $("#buttons_insert1").on('click', '#okcad1', function() {
       alert('hello world');
    }
    

    click 会将事件绑定到代码执行时存在于 DOM 中的元素,因此您需要事件委托技术。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-14
      • 2017-10-27
      • 1970-01-01
      • 2017-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-28
      相关资源
      最近更新 更多