javascript - How can I add an onclick handler on a dynamic element? - Stack Overflow

Here is the important part of my JS code:function createClose() {var cButton = document.createElement(&

Here is the important part of my JS code:

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";
}

The image gets created and appended, but there is no onClick event invoked when it is clicked. I also tried using an anonymous function, but that didn't work either.

No, I'm not going to use jQuery (although I believe you that it's easier).

Here is the important part of my JS code:

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";
}

The image gets created and appended, but there is no onClick event invoked when it is clicked. I also tried using an anonymous function, but that didn't work either.

No, I'm not going to use jQuery (although I believe you that it's easier).

Share edited Jun 16, 2010 at 19:13 Khan asked Jun 16, 2010 at 19:03 KhanKhan 2,9923 gold badges22 silver badges22 bronze badges 2
  • Is img in lines 3-5 supposed to be cButton? – Daniel Vandersluis Commented Jun 16, 2010 at 19:05
  • Is a JQuery solution ok? – S P Commented Jun 16, 2010 at 19:05
Add a ment  | 

2 Answers 2

Reset to default 3
input.setAttribute('onclick','handleClick();');
input = document.getElementById("my_window").appendChild(cButton);
input.onclick = function() { yourFunction(); };

This question is almost a duplicate of "Add onclick property to input with JavaScript" As an alternative way I've seen the use of input.setAttribute('onclick', 'yourFunction();'); too but cannot guarantee it works.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744911863a4600601.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信