Javascript - 动态添加具有 onClick 属性的按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22968844/
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-28 00:06:29  来源:igfitidea点击:

Javascript - Add button with onClick attribute dynamically

javascripthtml

提问by nicael

I am using this code, which adds button:

我正在使用此代码,它添加了按钮:

document.getElementById("items").innerHTML=document.getElementById("items").innerHTML+
('<input type="button" value="'+document.getElementById("add").value+'"><br>');

It works. Now i am adding onClickattribute:

有用。现在我添加onClick属性:

document.getElementById("items").innerHTML=document.getElementById("items").innerHTML+
    ('<input type="button" onClick="alert("'+document.getElementById("add").value+'")"
     value="'+document.getElementById("add").value+'"><br>');

I want to display an alert with button name (addis button id) if I click on button. But no alert displayed. Probably I made i mistake in onClick, because button is being added.
Whats wrong with my code?

add如果单击按钮,我想显示带有按钮名称(是按钮 ID)的警报。但没有显示警报。可能是我弄错了onClick,因为正在添加按钮。
我的代码有什么问题?

回答by adeneo

Do it the proper way

以正确的方式去做

var items  = document.getElementById("items"),
    button = document.createElement('input'),
    br     = document.createElement('br'),
    add    = document.getElementById("add").value;

button.type  = 'button';
button.value = add;
button.addEventListener('click', function() {
    alert(add);
}, false);

items.appendChild(button);
items.appendChild(br);

回答by nicael

I managed to do it!

我做到了!

 document.getElementById("items").innerHTML=document.getElementById("items").innerHTML
+('<input type="button" onClick="alert(\''+document.getElementById("add").value+'\')"
 value="'+document.getElementById("add").value+'"><br>')

I replaced "(double quote) with \'(single quote) in alert.
Works, button added, alert displayed.

我在警报"中用\'(单引号)替换了(双引号)。
有效,添加按钮,显示警报。