在操作发生之前触发 Javascript 事件
我正在尝试编写一个脚本,以便当我播放嵌入的声音对象时,我嵌入的图片也会发生变化。
function changePic() {
document.getElementById("sound").onclick = transform(document.getElementById("pic"));
}
function transform (pic) {
pic.src = "";
alert ("done");
}
问题是,当我加载页面时,即使我没有在声音对象上单击播放(autostart
设置为 false),Javascript 代码也会自动运行。有谁知道是什么原因造成的?
I am trying to write a script so that when I play an embedded sound object, a picture that I also have embedded will change.
function changePic() {
document.getElementById("sound").onclick = transform(document.getElementById("pic"));
}
function transform (pic) {
pic.src = "";
alert ("done");
}
The problem is that when I load the page, the Javascript code automatically runs even though I don't click play (autostart
is set to false) on the sound object. Does anyone have an idea as to what is causing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您编写
onclick = transform(...)
时,您调用transform
并将结果分配给onclick
。您需要将处理程序设置为调用
transform
的匿名函数,如下所示:但是,这是添加事件的错误方法。
您应该调用
element.addEventListener
/element.attachEvent
。 (或者只使用 jQuery)When you write
onclick = transform(...)
, you're callingtransform
and assigning the result toonclick
.You need to set the handler to an anonymous function that calls
transform
, like this:However, this is the wrong way to add events.
You should call
element.addEventListener
/element.attachEvent
. (or just use jQuery)