Javascript: onclick / onsubmit for dynamically created button

I dynamically create a button like I found on the Internet:

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

Unfortunately, it does not work and throws 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 

Solution with setAttribute function:

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

However, I want to call a class method (instead of a warning), and the b.onclick syntax looks better in this regard, I hope / think. is it onclick case senstive? Because if I write

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

I do not get the error above, but it still does not work, i.e. I do not get a warning. I am grateful for any advice.

As a bonus question: how can I avoid the current page reloading when a button is clicked? I just like to call the method and not cause the page to reload.

Thanks and best regards,

Christian

+6
source share
2 answers
 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); }; 
+24
source

Here is the version with input attributes:

  <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> 
0
source

Source: https://habr.com/ru/post/895068/


All Articles