开发者

Javascript event firing before action occurs

开发者 https://www.devze.com 2023-02-10 17:32 出处:网络
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.

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 (autosta开发者_如何学Pythonrt is set to false) on the sound object. Does anyone have an idea as to what is causing this?


When you write onclick = transform(...), you're calling transform and assigning the result to onclick.

You need to set the handler to an anonymous function that calls transform, like this:

document.getElementById("sound").onclick = function() {
    transform(document.getElementById("pic"));
};

However, this is the wrong way to add events.
You should call element.addEventListener / element.attachEvent. (or just use jQuery)

0

精彩评论

暂无评论...
验证码 换一张
取 消