简体   繁体   中英

Onmousedown in JavaScript not working --help!

The following function is supposed to execute during the "onload" event of my webpage.

function setUpTranslation() {
   var phrases = document.getElementsByTagName("p");

   for (i = 0; i<phrases.length; i++) {
      phrases[i].number = i;
      phrases[i].childNodes[1].innerHTML = french[i];

      phrases[i].childNodes[1].onMouseDown = alert("Hello World");
  }
}

Can anyone tell me why the alert happens each time through the For loop? I'm expecting that it would only happen when the user presses the mouse on one of the phrases in my list.

Someone said that onmousedown shouldn't be capitalized but when I do that I get an error saying "not implemented"

Thank you in advance for your help.

That's because you're calling it. What you want is to create a function that calls alert when it's called:

  phrases[i].childNodes[1].onMouseDown = function() {alert("Hello World");};

You're setting the onMouseDown event to the result of alert("Hello World"), not a function. Change it to something like this to keep it from running until you intend it to run:

phrases[i].childNodes[1].onMouseDown = function() { alert("Hello World"); };

This makes a function with the alert as the body of the function, and sets that function as the callback of the onMouseDown event.

phrases[i].childNodes[1].onMouseDown = alert("Hello World");

should be

phrases[i].childNodes[1].onMouseDown = function( ){ alert("Hello World"); };

otherwise it's return the value of alert as the handler (which is undefined and does nothing).

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