Javascript:动态创建按钮的 onclick/onsubmit
我以在互联网上找到的方式动态创建一个按钮:
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')");
但是,我想调用一个类方法(而不是警报),并且 b.我希望/认为 onclick 语法在这方面看起来更好。这个 onclick 区分大小写吗?因为如果我写,
b.onClick = function() {alert("OnClick");} // notice the spelling onclick vs onClick
我不会收到上面的错误,但它仍然不起作用,即我没有收到警报。我很感谢任何提示。
作为一个额外的问题:如何避免单击按钮时重新加载当前页面?我只是喜欢调用一个方法而不是导致页面重新加载。
谢谢并致以最诚挚的问候,
克里斯蒂安
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:
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 = 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是带有输入属性的版本:
Here is a version with attributes for input: