我可以强制jQuery使用Sizzle来评估选择器而不使用非标准选择器吗? [英] Can I force jQuery to use Sizzle to evaluate a selector without using non-standard selectors?

查看:110
本文介绍了我可以强制jQuery使用Sizzle来评估选择器而不使用非标准选择器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在现代浏览器中,jQuery使用 document.querySelectorAll()来提高使用有效CSS选择器时的性能。如果浏览器不支持选择器或 document.querySelectorAll()方法,则会回退到Sizzle。

In modern browsers, jQuery makes use of document.querySelectorAll() to boost performance when valid CSS selectors are used. It falls back to Sizzle if a browser doesn't support the selector or the document.querySelectorAll() method.

但是,我想在调试自定义选择器时始终使用Sizzle而不是本机实现。也就是说,我正在尝试提供的实现:nth-​​last-child() jQuery不支持的CSS3选择器之一。由于现代浏览器本身支持此选择器,因此它的工作方式与链接问题相同。正是这种行为干扰了调试我的自定义选择器,所以我想避免它。

However, I'd like to always use Sizzle instead of the native implementation when debugging a custom selector. Namely, I'm trying to come up with an implementation of :nth-last-child(), one of the CSS3 selectors that are not supported by jQuery. Since this selector is natively supported by modern browsers, it works as described in the linked question. It is precisely this behavior that's interfering with debugging my custom selector, though, so I'd like to avoid it.

我可以使用的一个便宜的黑客入侵非标准 jQuery选择器扩展,从而使选择器无效说话。例如,假设每个 li:nth-​​last-child(2)可见,我可以直接放入,转过来:

A cheap hack I can use is to drop in a non-standard jQuery selector extension, thereby "invalidating" the selector so to speak. For example, assuming every li:nth-last-child(2) is visible, I can simply drop that in, turning this:

$('li:nth-last-child(2)').css('color', 'red');

进入:

$('li:nth-last-child(2):visible').css('color', 'red');

这使得它始终由Sizzle评估。除此之外,这要求我假设我的页面元素可能是也可能不是。我真的不喜欢那样。更不用说,除非绝对必要,否则我不喜欢使用非标准选择器。

This causes it to always be evaluated by Sizzle. Except, this requires that I make an assumption of my page elements which may or may not be true. And I really don't like that. Not to mention, I dislike using non-standard selectors in general unless absolutely necessary.

有没有办法跳过本机 document.querySelectorAll( )支持它的浏览器中的方法并强制jQuery使用Sizzle来评估选择器,优选使用非标准选择器?可能,这需要调用另一个方法而不是 $(),但它比选择器黑客IMO要好得多。

Is there a way to skip the native document.querySelectorAll() method in browsers that support it and force jQuery to use Sizzle to evaluate a selector instead, that preferably doesn't employ the use of non-standard selectors? Likely, this entails calling another method instead of $(), but it's much better than a selector hack IMO.

推荐答案

你可以在加载jQuery之前将其设置为 null ,因此它认为它不受支持:

You could just set it to null before jQuery loads so it thinks it's not supported:

document.querySelectorAll = null;
//load jquery, will trigger not supported branch
//Optionally restore QSA here (save a reference) if needed

这应该是这个评估为 false

演示: http://jsbin.com/asipil/2/edit

评论 null 行并重新运行,你会发现它会变红。

Comment out the null line and rerun, and you will see it will turn red.

这篇关于我可以强制jQuery使用Sizzle来评估选择器而不使用非标准选择器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆