简体   繁体   中英

Why wont this on.Click event not work

///// FORM  ////
var form = document.getElementById("form");
form.setAttribute("style", "position: relative; margin-bottom: 5%;");

var newButton = document.createElement('button');
var newUl = document.createElement('ul');
var newLi = document.createElement('li');
var newInput = document.createElement('input');
form.appendChild(newButton);
newButton.setAttribute("style", "position: absolute; width: 15%; height: 40px; left: 42%; color: #B00000; background-color: white; font-size: 18px; border: 0px; ");
newButton.innerHTML = "Direct Message";
newButton.onClick = function() {
  alert("works");
};

Is there something wrong with my selection? just want the on.click to work on my button which is newButton created element.

Javascript property names are case-sensitive, it should be newButton.onclick .

Or you could move into the modern age and use addEventListener .

newButton.addEventListener("click", function() {
    alert("works");
});

Two things:

  1. You need to set the "type" attribute of the button to "button";
  2. It's "onclick", not "onClick"

The first thing prevents the button from submitting the surrounding <form> when it's clicked. The second will correctly set up the event handler.

this code doesn't work because the syntax is incorrect.

the correct syntax about the event 'click' is below:

newButton.onclick = function(){
 alert("works");
};

the event is write on the lower case.

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