adding onclick event to dynamically added button?

前端 未结 8 1528
天命终不由人
天命终不由人 2020-12-03 01:50

I am adding a button dynamically in html like below: On click of that button I want to call a Javascript function:

var but = document.createElement(\"button\         


        
8条回答
  •  一个人的身影
    2020-12-03 02:27

    I was having a similar issue but none of these fixes worked. The problem was that my button was not yet on the page. The fix for this ended up being going from this:

    //Bad code.
    var btn = document.createElement('button');
    btn.onClick = function() {  console.log("hey");  }
    

    to this:

    //Working Code.  I don't like it, but it works. 
    var btn = document.createElement('button');
    var wrapper = document.createElement('div');
    wrapper.appendChild(btn);
    
    document.body.appendChild(wrapper);
    var buttons = wrapper.getElementsByTagName("BUTTON");
    buttons[0].onclick = function(){  console.log("hey");  }
    

    I have no clue at all why this works. Adding the button to the page and referring to it any other way did not work.

提交回复
热议问题