分配onclick事件来运行 [英] assign onclick event to function
问题描述
我想调用函数onclick并将事件对象传递给函数:
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
}
所以我通过封闭对象(yt)分配clickedOffset然后调用progressBarClicked然后使用clickedOffset var。但我真正宁愿做的是这样的事情:
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);
因为它更紧凑。问题是,即使用户点击了或不执行这段代码... 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... yt.progressBarClicked(e).
有什么方法吗?
推荐答案
你的:
progressBarOuter.onclick = yt.progressBarClicked(e);
不会产生预期结果,因为您没有分配函数 yt.progressBarClicked
到 onclick
处理程序。您实际上正在调用该函数,因此将其返回值分配给 onclick
。
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
};
如果你不包装它, yt.progressBarClicked
将从窗口
对象调用,因此函数内的此
的值也将设置为窗口
对象。
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.
当然你也可以处理函数内部x位置的计算并且只是通过它的事件:
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);};
这篇关于分配onclick事件来运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!