JavaScript 中的 Onmousedown 不起作用 --help!
以下函数应该在我的网页的“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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您将 onMouseDown 事件设置为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:
This makes a function with the alert as the body of the function, and sets that function as the callback of the onMouseDown event.
那是因为你在调用它。您想要创建一个函数,当被调用时调用警报:
That's because you're calling it. What you want is to create a function that calls alert when it's called:
应该是
,否则它会返回
alert
的值作为处理程序(这是undefined
且不执行任何操作)。should be
otherwise it's return the value of
alert
as the handler (which isundefined
and does nothing).