JavaScript 中的 Onmousedown 不起作用 --help!

发布于 2024-08-19 14:01:42 字数 484 浏览 4 评论 0原文

以下函数应该在我的网页的“onload”事件期间执行。

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");
  }
}

谁能告诉我为什么每次通过 For 循环都会发生警报?我预计只有当用户将鼠标放在列表中的某个短语上时才会发生这种情况。

有人说 onmousedown 不应该大写,但是当我这样做时,我收到一条错误消息“未实现”,

提前感谢您的帮助。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

爱你是孤单的心事 2024-08-26 14:01:42

您将 onMouseDown 事件设置为alert("Hello World") 的结果,而不是函数。将其更改为类似以下内容,以防止其运行,直到您希望它运行:

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

这将创建一个将警报作为函数主体的函数,并将该函数设置为 onMouseDown 事件的回调。

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.

驱逐舰岛风号 2024-08-26 14:01:42

那是因为你在调用它。您想要创建一个函数,被调用时调用警报:

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

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");};
情绪 2024-08-26 14:01:42
phrases[i].childNodes[1].onMouseDown = alert("Hello World");

应该是

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

,否则它会返回 alert 的值作为处理程序(这是 undefined 且不执行任何操作)。

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文