Javascript: onclick/onsubmit for dynamically created button(Javascript:动态创建按钮的 onclick/onsubmit)
问题描述
我按照我在网上找到的方式动态创建一个按钮:
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
setAttribute 工作的解决方案:
The solution with setAttribute work:
b.setAttribute("onClick", "alert('OnClick')");
但是,我想调用一个类方法(而不是警报),我希望/认为 b.onclick 语法在这方面看起来更好.这个 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.
谢谢和最好的问候,
基督徒
推荐答案
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);
};
这篇关于Javascript:动态创建按钮的 onclick/onsubmit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Javascript:动态创建按钮的 onclick/onsubmit


- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Flexslider 箭头未正确显示 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01