Javascript-动态添加具有onClick属性的按钮 [英] Javascript - Add button with onClick attribute dynamically
本文介绍了Javascript-动态添加具有onClick属性的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用此代码,其中添加了按钮:
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>');
有效.现在,我要添加 onClick
属性:
It works. Now i am adding onClick
attribute:
document.getElementById("items").innerHTML=document.getElementById("items").innerHTML+
('<input type="button" onClick="alert("'+document.getElementById("add").value+'")"
value="'+document.getElementById("add").value+'"><br>');
如果我单击按钮,我想显示一个带有按钮名称的警报( add
是按钮ID).但是没有显示警报.可能是我在 onClick
上弄错了,因为正在添加按钮.
我的代码有什么问题?
I want to display an alert with button name (add
is 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?
推荐答案
以正确的方式进行操作
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);
这篇关于Javascript-动态添加具有onClick属性的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文