Javascript:动态创建按钮的onclick/onsubmit
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7066191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript: onclick/onsubmit for dynamically created button
提问by Christian
I dynamically create a button in the way I found in the Internet:
我按照我在网上找到的方式动态创建了一个按钮:
Page = function(...) {
...
};
Page.prototype = {
...
addButton : function() {
var b = content.document.createElement('button');
b.onclick = function() { alert('OnClick'); }
},
...
};
Unfortunately, it's not working and throwing the following error:
不幸的是,它不起作用并抛出以下错误:
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
The solution with setAttribute work:
使用 setAttribute 工作的解决方案:
b.setAttribute("onClick", "alert('OnClick')");
However, I want to call a class method (instead of alert), and the b.onclick syntax looks better in that respect, I hope/think. is this onclick case senstive? Because if I write
但是,我想调用一个类方法(而不是警报),我希望/认为 b.onclick 语法在这方面看起来更好。这个 onclick 区分大小写吗?因为如果我写
b.onClick = function() {alert("OnClick");} // notice the spelling onclick vs onClick
I don't get the error above, but it's still not working, i.e. I don't get the alert. I'm thankful for any tips.
我没有收到上述错误,但它仍然无法正常工作,即我没有收到警报。我很感激任何提示。
As a bonus question: How can I avoid that the current page is reload when the button is clicked? I just like call a method and not to cause a page reload.
作为奖励问题:如何避免在单击按钮时重新加载当前页面?我只是喜欢调用一个方法而不是导致页面重新加载。
Thanks and best regards,
谢谢和最好的问候,
Christian
基督教
回答by Walialu
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);
};
回答by Avinash
Here is a version with attributes for input:
这是一个带有输入属性的版本:
<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>