• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

分配onclick事件来运行

用户头像
it1352
帮助1

问题说明

我想调用函数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).

有什么方法吗?

正确答案

#1

你的:

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);};

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfjjhc
系列文章
更多 icon
同类精品
更多 icon
继续加载