基于 Modernizr 的不同方法:单击与悬停

发布于 2024-11-07 02:23:20 字数 420 浏览 1 评论 0原文

我希望能够根据 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绝對不後悔。 2024-11-14 02:23:20

是的,使用替代对象访问符号 [] 可以很容易做到这一点:

var eventName = Modernizr.touch ? 'click' : 'mouseover';
$(el)[eventName](stuff);

这里的相关事实是,由于 Javascript 函数是一等对象,因此可以像任何其他对象属性一样访问它们。例如,您可以这样做:

var foo = { bar: 100 };
console.log(foo.bar);
console.log(foo['bar']);

两条线实际上是相同的。

由于 clickmouseover 是 jQuery 选择的属性,因此您可以像这样访问它们。例如,您可以(如果您愿意)将 click 方法调用为 $(el)['click']()。没有意义,但你可以做到。

在这里,您可以利用这种替代语法来处理要调用的函数取决于其他因素的情况。

编辑:有关此内容的更多文档,请参阅有关“成员操作员”的 MDC 页面。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文