基于Modernizr的不同方法:点击vs悬停 [英] Different methods based on Modernizr: click vs hover
问题描述
我希望能够根据Modernizr的touch / no-touch输出在.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);
是的,使用替代对象访问表示法 []
:
var eventName = Modernizr.touch? 'click':'mouseover';
$(el)[eventName](stuff);
这里的相关事实是,由于Javascript函数是一流的对象,因此可以通过与其他对象属性一样。例如,你可以这样做:
var foo = {bar:100};
console.log(foo.bar);
console.log(foo ['bar']);
两条线实际上是相同的。
由于单击
和 mouseover
是jQuery选择的属性,因此可以像这样访问它们。例如,你可以(如果你这么倾向于)将点击
方法称为 $(el)['click']()
。没有意义,但你可以做到。
在这里,您可以利用这种替代语法来处理调用函数取决于其他因素。
编辑:有关此方面的更多文档,请参阅关于会员运营商的MDC页面。
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);
Yes, this is easy with the alternative object access notation []
:
var eventName = Modernizr.touch ? 'click' : 'mouseover';
$(el)[eventName](stuff);
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:
var foo = { bar: 100 };
console.log(foo.bar);
console.log(foo['bar']);
The two lines are practically identical.
Since click
and mouseover
are properties of a jQuery selection, you can access them like this. For instance, you could (if you were so inclined) call the click
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".
这篇关于基于Modernizr的不同方法:点击vs悬停的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!