JavaScript:动态创建按钮的onclick/onsubmit

18

我以在互联网上找到的方式动态创建了一个按钮:

 Page = function(...) {
   ...
 };

 Page.prototype = {
   ...
   addButton : function() {
     var b = content.document.createElement('button');
     b.onclick = function() { alert('OnClick'); }
   },
   ...
 };

不幸的是,它未能工作并抛出以下错误:

  Error: [Exception... "Component is not available"  nsresult: "0x80040111
  (NS_ERROR_NOT_AVAILABLE)"  location: "JS frame :: chrome://knowledgizer/content
  /knowledgizer.js :: <TOP_LEVEL> :: line 137"  data: no]
  Source File: chrome://browser/content/tabbrowser.xml Line: 434

使用 setAttribute 的解决方案有效:

b.setAttribute("onClick", "alert('OnClick')");

然而,我想调用一个类方法(而不是alert),b.onclick语法在这方面看起来更好,我希望/认为。这个onclick区分大小写吗?因为如果我写成

b.onClick = function() {alert("OnClick");} // notice the spelling onclick vs onClick

我没有收到上述错误,但它仍然无法工作,即我没有收到警报。感谢任何提示。

额外的问题:当单击按钮时,如何避免重新加载当前页面?我只想调用一个方法而不是导致页面重新加载。

谢谢和最好的问候,

Christian

2个回答

54
var foo = function(){
  var button = document.createElement('button');
  button.innerHTML = 'click me';
  button.onclick = function(){
    alert('here be dragons');return false;
  };
  // where do we want to have the button to appear?
  // you can append it to another element just by doing something like
  // document.getElementById('foobutton').appendChild(button);
  document.body.appendChild(button);
};

谢谢,你的例子在这里也起作用。我注意到我经常使用content.document.createElement()而不是document.createElement()。到目前为止,我没有遇到任何问题,但显然有很大的区别。当我在代码中删除'content.'时,它可以工作。 - Christian
1
我找到了一个可行的解决方案——为按钮添加事件监听器,具体请参考这里:https://dev59.com/tlrUa4cB1Zd3GeqPiUhR - Christian
你真是个明星。在IE9上,除了这个之外,没有任何东西能解决我的问题。我试图使用jQuery动态添加按钮,在所有浏览器中都有效,但在IE9中却无效。 - Amc_rtty
1
嘿!我正在做类似的事情。我使用for循环创建了大约10个按钮。在警报中,我需要显示按钮上的数字。怎么做? - abc
@abc 我猜你正在使用一个带有计数器的for循环,就像这样 for(var i =0; i<array.length ;i++){....... button.onclick = function(){alert(I);};} - Walialu

1

以下是带有输入属性的版本:

 <button onclick="myFun()">Add More</button>
    <script>
        function myFun() {
            var x = document.createElement("INPUT");
            x.setAttribute("type", "file");
            x.setAttribute("id", "file");
            document.body.appendChild(x);
            x.onchange = function () {
                hello();
            };
            btn.appendChild(t);
            document.body.appendChild(btn);
        }
        function hello() {
            window.alert("hello!");
        }
    </script>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接