adding onclick event to dynamically added button?

前端 未结 8 1519
天命终不由人
天命终不由人 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:37

    Try
    but.addEventListener('click', yourFunction) Note the absence of parantheses () after the function name. This is because you are assigning the function, not calling it.

    0 讨论(0)
  • 2020-12-03 02:39

    Try this:

    var inputTag = document.createElement("div");              
    inputTag.innerHTML = "<input type = 'button' value = 'oooh' onClick = 'your_function_name()'>";    
    document.body.appendChild(inputTag);
    

    This creates a button inside a DIV which works perfectly!

    0 讨论(0)
提交回复
热议问题