简体   繁体   中英

HTML and JavaScript - How do you add a click event to a div

I've been following examples but my fiddle isn't working. Here is the code:

  var showMessage; var divTag = document.getElementById("myDiv"); divTag.onClick = showMessage(); showMessage = function() { alert("You clicked me."); } 
 <div id="myDiv" style="height: 100px; width: 100px; background-color: pink;"> </div> 

I'm probably missing something stupid but I cannot see it. I read out here that it is possible to put a click event on a div. Anybody know what I am doing wrong?

PS Yeah, I don't know how to decipher or fix the error.

Change your JS to this:

function showMessage() {
  alert("You clicked me.");
}

var divTag = document.getElementById("myDiv");
divTag.addEventListener('click', showMessage);

Your code: divTag.onClick = showMessage(); was calling the response of the function showMessage instead of the function.

showMessage was called and its return value ( undefined ) is what you passed to the onClick property.

Minor issue: If you want this page to be used by Blind users that use a screen reader it would be better to use a <button> or an <a> tag. Either that or you need to emulate all of the things needed to get the screen readers to work correctly.

You had several problems:

  • You defined "showMessage" as an empty variable, then tried to call it as a function, then defined it as a function.
  • onClick is not the same thing as onclick .
  • You invoked showMessage when trying to assign it to the onclick event, instead of assigning the function itself you ended up assigning its (empty) return value.

Here is the corrected version of your code:

  showMessage = function() { alert("You clicked me."); } var divTag = document.getElementById("myDiv"); divTag.onclick = showMessage; 
 <div id="myDiv" style="height: 100px; width: 100px; background-color: pink;"></div> 

That's vanilla JS. Since the question is also tagged "jQuery", here's the jQuery version of the same thing:

$('#myDiv').on("click",function() {alert("you clicked me")}); 

Since you've tagged jQuery I'll just give you the jQuery solution:

$('#myDiv').click(showMessage);

But make sure you set the showMessage function before (above) that jQuery click event binding.

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