adding onclick event to dynamically added button?

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

    but.onclick = function() { yourjavascriptfunction();};

    or

    but.onclick = function() { functionwithparam(param);};

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

    This code work good to me and look more simple. Necessary to call a function with specific parameter.

    var btn = document.createElement("BUTTON");  //<button> element
    var t = document.createTextNode("MyButton"); // Create a text node
    btn.appendChild(t);   
    
    btn.onclick = function(){myFunction(myparameter)};  
    document.getElementById("myView").appendChild(btn);//to show on myView
    
    0 讨论(0)
  • 2020-12-03 02:24

    try this:

    but.onclick = callJavascriptFunction;
    

    or create the button by wrapping it with another element and use innerHTML:

    var span = document.createElement('span');
    span.innerHTML = '<button id="but' + inc +'" onclick="callJavascriptFunction()" />';
    
    0 讨论(0)
  • 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.

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

    Remove the () from your expressions that are not working will get the desired results you need.

    but.setAttribute("onclick",callJavascriptFunction);
    but.onclick= callJavascriptFunction;
    document.getElementById("but").onclick=callJavascriptFunction;
    
    0 讨论(0)
  • 2020-12-03 02:33
    but.onclick = callJavascriptFunction;
    

    no double quotes no parentheses.

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