在现代浏览器中,jQuery 使用 document.querySelectorAll()
来提高使用有效 CSS 选择器时的性能。如果浏览器不支持选择器或 document.querySelectorAll()
方法,它将返回到 Sizzle。
但是,我希望在调试自定义选择器时始终使用 Sizzle 而不是 native 实现。也就是说,我正在尝试实现 :nth-last-child()
, one of the CSS3 selectors that are not supported by jQuery .由于现代浏览器原生支持此选择器,因此它按照链接问题中的描述工作。不过,正是这种行为干扰了我自定义选择器的调试,所以我想避免它。
我可以使用的一个廉价 hack 是放入一个非标准的 jQuery selector extension ,从而使选择器“无效”可以这么说。例如,假设每个 li:nth-last-child(2)
都是 visible ,我可以简单地把它放进去,把这个:
$('li:nth-last-child(2)').css('color', 'red');
进入这个:
$('li:nth-last-child(2):visible').css('color', 'red');
这导致它总是由 Sizzle 评估。除此之外,这要求我对我的页面元素做出假设,这些元素可能是真实的,也可能不是真实的。我真的不喜欢那样。更不用说,除非绝对必要,否则我通常不喜欢使用非标准选择器。
有没有办法在支持它的浏览器中跳过 native document.querySelectorAll()
方法并强制 jQuery 使用 Sizzle 来评估选择器,最好 不会 使用非标准选择器?很可能,这需要调用另一种方法而不是 $()
,但它比选择器 hack IMO 好得多。
最佳答案
您可以在 jQuery 加载之前将它设置为 null
,这样它就认为它不受支持:
document.querySelectorAll = null;
//load jquery, will trigger not supported branch
//Optionally restore QSA here (save a reference) if needed
这应该是 this评估为 false
演示:http://jsbin.com/asipil/2/edit
注释掉 null
行并重新运行,您会看到它会变成红色。
关于javascript - 我可以强制 jQuery 使用 Sizzle 来评估选择器而不使用非标准选择器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11748141/