Different methods based on Modernizr: click vs hover

家住魔仙堡 提交于 2019-12-11 13:06:41

问题


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

回答1:


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".



来源:https://stackoverflow.com/questions/5985430/different-methods-based-on-modernizr-click-vs-hover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!