【问题标题】:How can I add an onclick handler on a dynamic element?如何在动态元素上添加 onclick 处理程序?
【发布时间】:2010-06-16 19:03:53
【问题描述】:

这是我的 JS 代码的重要部分:

function createClose() {
  var cButton = document.createElement("img");
  cButton.src = "close.gif";
  cButton.style.cursor = "pointer";
  cButton.onclick = closeWindow;

  document.getElementById("my_window").appendChild(cButton);
}

function closeWindow() {
  document.getElementById("my_window").style.display = "none";
}

图像被创建并附加,但在单击时没有调用 onClick 事件。我也尝试过使用匿名函数,但也没有用。

不,我不会使用 jQuery(尽管我相信你会更容易)。

【问题讨论】:

  • 第 3-5 行中的 img 应该是 cButton 吗?
  • JQuery 解决方案好吗?

标签: javascript event-handling


【解决方案1】:
input.setAttribute('onclick','handleClick();');

【讨论】:

    【解决方案2】:
    input = document.getElementById("my_window").appendChild(cButton);
    input.onclick = function() { yourFunction(); };
    

    这个问题几乎与“Add onclick property to input with JavaScript”重复 作为另一种方式,我也看到了input.setAttribute('onclick', 'yourFunction();'); 的使用,但不能保证它有效。

    【讨论】:

    • 我可以在将事件处理程序附加到文档之前添加它吗?正如我所说,匿名函数在这种情况下不起作用。
    • 看看提到的和链接的问题,他们会在像你说的那样附加它之前这样做(:希望它有帮助
    • setAttribute() 路由对我有用,现在我只需要检查它的跨浏览器兼容性...
    • 试用后告诉我,这样我就不用自己测试跨浏览器的效果了,谢谢。
    • input 在第 1 行之后指的是什么?第 2 行和问题中的 onclick 分配有什么区别?
    猜你喜欢
    • 2018-08-05
    • 1970-01-01
    • 2021-11-08
    • 2019-05-17
    • 2011-08-11
    • 1970-01-01
    • 2010-09-19
    • 2023-03-30
    • 2012-04-10
    相关资源
    最近更新 更多