Javascript:动态创建按钮的 onclick/onsubmit [英] Javascript: onclick/onsubmit for dynamically created button

查看:23
本文介绍了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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆