基于 Modernizr 的不同方法:单击与悬停
我希望能够根据 Modernizr 的触摸/非触摸输出在 .mouseover 和 .click 事件之间进行选择。
if (Modernizr.touch) {
$(el).click(stuff);
$(el).click(stuff);
} else {
$(el).mouseover(stuff);
$(el).mouseover(stuff);
}
但我不想把所有这些东西写两次。是否可以定义一些东西,以便我可以调用:
if (Modernizr.touch) {correctEvent = click} else {correctEvent = mouseover}
$(el).correctEvent(stuff);
$(el).correctEvent(stuff);
I want to be able to choose between .mouseover and .click events based on Modernizr's touch/no-touch output.
if (Modernizr.touch) {
$(el).click(stuff);
$(el).click(stuff);
} else {
$(el).mouseover(stuff);
$(el).mouseover(stuff);
}
But I don't want to write out all that stuff twice. Is it possible to define something so that I can just call:
if (Modernizr.touch) {correctEvent = click} else {correctEvent = mouseover}
$(el).correctEvent(stuff);
$(el).correctEvent(stuff);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,使用替代对象访问符号
[]
可以很容易做到这一点:这里的相关事实是,由于 Javascript 函数是一等对象,因此可以像任何其他对象属性一样访问它们。例如,您可以这样做:
两条线实际上是相同的。
由于
click
和mouseover
是 jQuery 选择的属性,因此您可以像这样访问它们。例如,您可以(如果您愿意)将click
方法调用为$(el)['click']()
。没有意义,但你可以做到。在这里,您可以利用这种替代语法来处理要调用的函数取决于其他因素的情况。
编辑:有关此内容的更多文档,请参阅有关“成员操作员”的 MDC 页面。
Yes, this is easy with the alternative object access notation
[]
:The relevant fact here is that, since Javascript functions are first-class objects, they can be accessed in the same way as any other object property. For instance, you can do this:
The two lines are practically identical.
Since
click
andmouseover
are properties of a jQuery selection, you can access them like this. For instance, you could (if you were so inclined) call theclick
method as$(el)['click']()
. There would be no point, but you could do it.Here, you can take advantage of this alternative syntax to handle the case where the function to call depends on other factors.
Edit: For more documentation on this, see the MDC page on "member operators".