how to call onclick function on dynamically created button in javascript

前端 未结 4 1068
花落未央
花落未央 2021-02-14 21:45
var del = document.createElement(\'input\');
del.type = \'button\';
del.name = \'delll\';
del.value = \'del\';
del.onClick = \'alert(\"hi  javascript\")\';
相关标签:
4条回答
  • 2021-02-14 22:12

    Try like this

        var del = document.createElement('input');
        del.setAttribute('type', 'button');
        del.setAttribute('name', 'delll');
        del.setAttribute('value', 'del');
        del.setAttribute('onClick', 'alert("hi  jaavscript")');
    
    0 讨论(0)
  • 2021-02-14 22:26

    So to answer the question in details:

    del.onclick = '' does not "execute" something within quotes. If you want to execute/call a function, you would want to pass the function as a parameter.

    i.e

    del.onclick = function() { alert('hi there!')}
    
    0 讨论(0)
  • 2021-02-14 22:27
    del.onclick = function () {
        alert("hi  jaavscript");
    };
    

    Use small "C" in onClick and pass a function for it.

    Demo here

    0 讨论(0)
  • 2021-02-14 22:30

    set the onclick (all lower case) to an anonymous function

    del.onclick = function(){ alert('hi javascript');};
    

    note the function is not in quotes like other attributes

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