Javascript event firing before action occurs
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)
精彩评论