如何使用 JavaScript 创建带有点击事件的动态按钮?
我试过了,但是当我点击添加按钮时,会出现一条警告消息!这不是我想要的 - 我希望能够单击动态创建的按钮。
<script language="javascript">
function add(type) {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", type);
element.setAttribute("value", type);
element.setAttribute("name", type);
element.setAttribute("onclick", alert("blabla"));
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
}
</script>
最佳答案
哇,你很接近。在评论中编辑:
function add(type) {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.type = type;
element.value = type; // Really? You want the default value to be the type string?
element.name = type; // And the name too?
element.onclick = function() { // Note this is a function
alert("blabla");
};
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
}
document.getElementById("btnAdd").onclick = function() {
add("text");
};
<input type="button" id="btnAdd" value="Add Text Field">
<p id="fooBar">Fields:</p>
现在,您可以考虑使用 addEventListener
,而不是设置元素的 onclick
属性(称为“DOM0 事件处理”) (在大多数浏览器上)或 attachEvent
(在除最近的 Microsoft 浏览器之外的所有浏览器上)——您必须检测并处理这两种情况——因为这种称为“DOM2 事件处理”的形式具有更大的灵 active 。但是,如果您不需要多个处理程序等,旧的 DOM0 方法就可以正常工作。
与上述不同:您可以考虑使用一个很好的 JavaScript 库,例如 jQuery , Prototype , YUI , Closure , 或 any of several others .它们消除了浏览器的差异,如 addEventListener
/attachEvent
东西,提供有用的实用功能,以及各种其他东西。很明显,库可以做的事没有一个是你做不到的,因为库只是 JavaScript 代码。但是,当您使用具有广泛用户群的优秀库时,您将受益于其他人已经完成的处理这些浏览器差异等的大量工作。
关于javascript - 在 JavaScript 中创建带有点击事件的动态按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7707074/