javascript 如何在javascript中动态创建的按钮上调用onclick函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18821647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:20:16  来源:igfitidea点击:

how to call onclick function on dynamically created button in javascript

javascriptbuttondynamically-generated

提问by user2750762

var del = document.createElement('input');
del.type = 'button';
del.name = 'delll';
del.value = 'del';
del.onClick = 'alert("hi  javascript")';

Here I have dynamically created a input type BUTTON and now I want to call function on button click event. I am using onClick();function for this. In the above code all is working fine but del.onclickis not working as I want (for generating alert for demo)

在这里,我动态创建了一个输入类型 BUTTON,现在我想在按钮单击事件上调用函数。我正在onClick();为此使用函数。在上面的代码中,一切正常,但del.onclick没有按我想要的方式工作(用于为演示生成警报)

I am not using any jquery code in this program so please don't use any jquery code.

我没有在这个程序中使用任何 jquery 代码,所以请不要使用任何 jquery 代码。

采纳答案by Paul Nelson

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

将 onclick(全部小写)设置为匿名函数

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

note the function is not in quotes like other attributes

请注意,该函数不像其他属性那样用引号引起来

回答by Sergio

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

Use small "C"in onClickand pass a function for it.

使用 small "C"inonClick并为它传递一个函数。

Demo here

演示在这里

回答by Nitish

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

回答by Neeraj

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.

del.onclick = '' 不会在引号内“执行”某些内容。如果要执行/调用函数,则需要将该函数作为参数传递。

i.e

IE

del.onclick = function() { alert('hi there!')}