使用JavaScript中的单击事件创建动态按钮

时间:2011-10-09 22:44:13

标签: javascript html

如何使用带有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>

4 个答案:

答案 0 :(得分:50)

哇,你很亲密。编辑评论:

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(在大多数浏览器上)或attachEvent(在...上),而不是设置元素的onclick属性(称为“DOM0事件处理”)。除了最新的微软浏览器之外的所有东西 - 你必须检测并处理这两种情况 - 因为这种形式称为“DOM2事件处理”,具有更大的灵活性。但是如果你不需要多个处理程序等,旧的DOM0方式可以正常工作。


与上述内容分开:您可以考虑使用一个好的JavaScript库,如jQueryPrototypeYUIClosureany of several others。它们可以平滑浏览器差异,例如addEventListener / attachEvent,提供有用的实用程序功能以及其他各种功能。显然,没有一个库可以做任何你不能做的事情,因为库只是JavaScript代码。但是,当您使用具有广泛用户群的优秀库时,您可以获得其他人处理这些浏览器差异等已经完成的巨大工作量的好处。

答案 1 :(得分:3)

这样:

element.setAttribute("onclick", alert("blabla"));

应该是:

element.onclick = function () {
  alert("blabla");
}

因为您调用alert而不是将alert作为属性

中的字符串

答案 2 :(得分:3)

<!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>

答案 3 :(得分:1)

首先,您需要更改此行:

element.setAttribute("onclick", alert("blabla"));

对于这样的事情:

element.setAttribute("onclick", function() { alert("blabla"); });

其次,在以这种方式附加事件时,您可能会遇到浏览器兼容性问题。您可能需要使用.attachEvent / .addEvent,具体取决于哪个浏览器。我还没有尝试过一段时间手动设置事件处理程序,但我记得firefox和IE对它们的处理方式不同。

相关问题