哪个更适合用作性能视角:
$(".div1 h2, .div1 h3")
Run Code Online (Sandbox Code Playgroud)
要么
$(".div1").find("h2, h3")
Run Code Online (Sandbox Code Playgroud) 有没有办法测试选择器是否匹配给定的DOM元素?优选地,不使用像Sizzle这样的外部库.这是一个库,我想尽量减少"核心"库所需的第三方插件的数量.如果它最终需要Sizzle我只是将它作为插件添加到库中,以便那些想要它将启用的功能.
例如,我可以做类似的事情:
var element = <input name="el" />
matches("input[name=el]", element) == true
Run Code Online (Sandbox Code Playgroud)
编辑:在考虑了更多之后,我提出了一个解决方案,这在技术上有效,但在效率方面似乎不是最佳的:
function matchesSelector(selector, element) {
var nodeList = document.querySelectorAll(selector);
for ( var e in nodeList ) {
return nodeList[e] === element;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
基本上,函数使用给定的选择器查询整个文档,然后迭代nodeList.如果给定元素在nodeList中,则返回true,如果不是,则返回false.
如果有人能够提出更有效的答案,我很乐意将他们的答案标记为答案.
编辑:Flavius Stef向我指出了Firefox 3.6+,mozMatchesSelector的浏览器特定解决方案.我还发现Chrome的等价物(版本兼容性未知,它可能在Safari或其他webkit浏览器上有效或不起作用):, webkitMatchesSelector这与Firefox实现基本相同.我还没有找到IE浏览器的任何原生实现.
对于上面的示例,用法将是:
element.(moz|webkit)MatchesSelector("input[name=el]")
Run Code Online (Sandbox Code Playgroud)
似乎W3C也在Selectors API Level 2(此时仍为草案)规范中解决了这个问题.matchesSelector一旦批准,将成为DOM元素的方法.
W3C用法: element.matchesSelector(selector)
Since that specification is still a draft and there is a lag time before popular browsers implement the methods …
为什么不能eval在with语句下使用范围变量?
例如:
(function (obj) {
with (obj) {
console.log(a); // prints out obj.a
eval("console.log(a)"); // ReferenceError: a is not defined
}
})({ a: "hello" })
Run Code Online (Sandbox Code Playgroud)
编辑:正如知识渊博的CMS所指出的,这似乎是一个浏览器错误(使用WebKit控制台的浏览器).
如果有人想知道我试图提出什么憎恶,那将需要"邪恶" eval和with- 我试图看看我是否可以获得一个函数(用作回调)在另一个上下文中执行而不是它被定义为.不,我可能(咳)不会在任何地方使用它...比任何事都更好奇.
(function (context,fn) {
with (context)
eval("("+fn+")()");
})({ a: "hello there" }, function () { console.log(a); })
Run Code Online (Sandbox Code Playgroud)