简体   繁体   中英

How do I get a created element (a button) to run a function?

This is the code I used to create the button:

var dfom = document.createElement('div');
dfom.setAttribute("id","options");
dfom.innerHTML = "<input type=\"button\" value=\"Say HI\" onclick=\get()\ />";
dfom.style.padding = '10px';
document.body.insertBefore(dfom, document.body.firstChild);

The button is created fine; it displays correctly. So to test it, I did this:

function get()
{
alert("HI");
}

However, when I click the button nothing happens. Any help, please? Thanks!

The function name should also be in quotes, ie onClick="get();" . Also read up on Event Listeners whenever you get the time, for instace here .

If you want to write correct JavaScript code, then you should do it as follows:

var dfom = document.createElement("div"),
    button = document.createElement("input");

button.type = "button";
button.value = "Say HI";
button.addEventListener("click", function() {
    alert("HI");
}, false);

dfom.id = "options";
dfom.style.padding = "10px";
dfom.appendChild(button);

document.body.insertBefore(dfom, document.body.firstChild);

DEMO: http://jsfiddle.net/TKdYh/

The \\ should be \\" around get() , but there are more considerations: namely the get function actually has to be defined outside of onload or another callback since it needs to be available globally. You would need a setup similar to this:

http://jsfiddle.net/CZ2y4/

...which defines get outside of the onLoad callback, which makes it available to onclick .

Also, use standard event bindings rather than onclick :

dfom.innerHTML = "<input type=\"button\" value=\"Say HI\">";
dfom.firstChild.addEventListener('click', get);

http://jsfiddle.net/CZ2y4/1/

The following works for me:

window.onload = function() {
  var dfom = document.createElement('div');
  dfom.id = "options";
  dfom.innerHTML = '<input type="button" value="Say HI" onclick="get()">';
  dfom.style.padding = '10px';
  document.body.insertBefore(dfom, document.body.children[0]);
}

function get() {
  alert("HI");
}

Some things to note:

  1. For standard DOM properties, it's usually better to just set the property, don't use setAttribute as it is inconsistently implemented.

  2. It's clearer to use single quotes for script and double quotes for makrup, that way you don't have to use as many backslashes to quote quotes

  3. Strictly, HTML attribute values only need to be quoted if they contain certain characters . It's easier to just quote them all rather than remember what that set of characters is. Browsers are also very tolerant so you can get away with unquoted characters that should be quoted in some browsers but not others.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM