assign onclick event to function
I want to call a function onclick and pass the event object to the function:
progressBarOuter.onclick = function(e) {
var x; if (!e) {
x=window.event.clientX;
}
else {
x = e.clientX
}
yt.clickedOffset = x; yt.progressBarClicked
}
So i'm assigning clickedOffset to by enclosing object (yt) and then calling progressBarClicked which then uses the clickedOffset var. But what I actually would rather be doing is something like this:
progressBarOuter.onclick = yt.progressBarClicked(e);
Because it's much more compact. Problem is that even if the user has clicked or not this bit of code is executed..开发者_StackOverflow社区. yt.progressBarClicked(e).
Is there any way around this?
Your:
progressBarOuter.onclick = yt.progressBarClicked(e);
doesn't yield the expected result, because you're not assigning the function yt.progressBarClicked
to the onclick
handler. You are actually calling the function and therefore assigning its return value to onclick
.
The shortest working thing you can get without breaking anything is this:
progressBarOuter.onclick = function(e){
yt.progressBarClicked((e || window.event).clientX); // pass the x position as a parameter
};
If you don't wrap it, yt.progressBarClicked
will be called from the window
object and therefore the value of this
inside the function will be also set to the window
object.
Of course you could also handle the calculation of the x position inside the function and just pass the event to it:
progressBarOuter.onclick = function(e){yt.progressBarClicked(e);};
Try
progressBarOuter.onclick = yt.progressBarClicked;
But technically this is not the same as your original code. The calculation for the mouse position (clientX) is missing altogether.
精彩评论