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

Mus*_*ici 33 html javascript

如何使用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/ attachEventthing,提供有用的实用程序功能以及其他各种功能.显然,没有一个库可以做任何你不能做的事情,因为库只是JavaScript代码.但是,当你使用一个好的图书馆有广泛的用户基础,你得到的好处巨大已经被其他人处理这些浏览器的差异,等完成的工作数量


new*_*rld 6

这:

element.setAttribute("onclick", alert("blabla"));
Run Code Online (Sandbox Code Playgroud)

应该:

element.onclick = function () {
  alert("blabla");
}
Run Code Online (Sandbox Code Playgroud)

因为您调用警报而不是将警报作为属性中的字符串推送

  • 不不不*。它应该是`el.onclick=function(){}`。 (4认同)
  • @mekici - 这没有任何意义。*哪部分不起作用*? (3认同)
  • @mekici - 当您在该评论中使用表单时,您正在使用“eval()”来评估“alert()”。这通常被认为是一个坏主意(无论是在性能还是安全方面)。使用设置为处理程序的匿名函数(如 neworld 和 TJ Crowder 那样)是公认的最佳实践。 (2认同)

小智 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)