在现代浏览器中,jQuery 利用document.querySelectorAll()
使用有效的 CSS 选择器时提高性能。如果浏览器不支持选择器或document.querySelectorAll()
method.
但是,在调试自定义选择器时,我希望始终使用 Sizzle 而不是本机实现。也就是说,我正在尝试提出一个实现:nth-last-child()
, jQuery 不支持的 CSS3 选择器之一 https://stackoverflow.com/questions/11745274/what-css3-selectors-does-jquery-really-support-e-g-nth-last-child。由于现代浏览器本身支持此选择器,因此它的工作原理如链接问题中所述。不过,正是这种行为干扰了我的自定义选择器的调试,所以我想避免它。
我可以使用的一个廉价技巧是添加一个非标准的jQuery 选择器扩展 http://api.jquery.com/category/selectors/jquery-selector-extensions,从而可以说使选择器“无效”。例如,假设每个li:nth-last-child(2)
is visible http://api.jquery.com/visible-selector,我可以简单地把它放进去,把它变成:
$('li:nth-last-child(2)').css('color', 'red');
进入这个:
$('li:nth-last-child(2):visible').css('color', 'red');
这导致它始终由 Sizzle 进行评估。除此之外,这要求我对我的页面元素做出假设,该假设可能是真的,也可能不是。我真的不喜欢这样。更不用说,除非绝对必要,否则我通常不喜欢使用非标准选择器。
有没有办法跳过原生document.querySelectorAll()
方法在支持它的浏览器中,并强制 jQuery 使用 Sizzle 来评估选择器,最好是doesn't使用非标准选择器?可能,这需要调用另一个方法而不是$()
,但在我看来,它比选择器 hack 好得多。
你可以将其设置为null
在 jQuery 加载之前,它认为它不受支持:
document.querySelectorAll = null;
//load jquery, will trigger not supported branch
//Optionally restore QSA here (save a reference) if needed
这应该使this https://github.com/jquery/sizzle/blob/master/sizzle.js#L1316评估为false
Demo: http://jsbin.com/asipil/2/edit http://jsbin.com/asipil/2/edit
注释掉null
线并重新运行,你会看到它会变成红色。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)