开发者

How can I add an onclick handler on a dynamic element?

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).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜