how to call onclick function on dynamically created button in javascript

主宰稳场 提交于 2019-12-03 12:28:48

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

del.onclick = function () {
    alert("hi  jaavscript");
};

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

Demo here

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")');

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!')}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!