如何使用JavaScript创建带有click事件的动态按钮?
我尝试了这个,但是当我点击添加按钮时,会显示一条警告消息!这不是我想要的 - 我希望能够点击动态创建的按钮.
<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>
Run Code Online (Sandbox Code Playgroud)
T.J*_*der 51
哇,你很亲密.编辑评论:
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");
};
Run Code Online (Sandbox Code Playgroud)
<input type="button" id="btnAdd" value="Add Text Field">
<p id="fooBar">Fields:</p>
Run Code Online (Sandbox Code Playgroud)
现在,onclick
您可以考虑使用addEventListener
(在大多数浏览器上)或attachEvent
(在所有但非常新的Microsoft浏览器上) - 而不是设置元素的属性(称为"DOM0事件处理" ) - 您必须检测并处理这两种情况 - 这种形式称为"DOM2事件处理",具有更大的灵活性.但是如果你不需要多个处理程序等,旧的DOM0方式可以正常工作.
与上面分开:您可以考虑使用一个好的JavaScript库,如jQuery,Prototype,YUI,Closure或其他几个.它们可以平滑浏览器差异,例如addEventListener
/ attachEvent
thing,提供有用的实用程序功能以及其他各种功能.显然,没有一个库可以做任何你不能做的事情,因为库只是JavaScript代码.但是,当你使用一个好的图书馆有广泛的用户基础,你得到的好处巨大已经被其他人处理这些浏览器的差异,等完成的工作数量
这:
element.setAttribute("onclick", alert("blabla"));
Run Code Online (Sandbox Code Playgroud)
应该:
element.onclick = function () {
alert("blabla");
}
Run Code Online (Sandbox Code Playgroud)
因为您调用警报而不是将警报作为属性中的字符串推送
小智 5
<!DOCTYPE html>
<html>
<body>
<p>Click the button to make a BUTTON element with text.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var btn = document.createElement("BUTTON");
var t = document.createTextNode("CLICK ME");
btn.setAttribute("style","color:red;font-size:23px");
btn.appendChild(t);
document.body.appendChild(btn);
btn.setAttribute("onclick", alert("clicked"));
}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)