Ste*_*fan 21 javascript css-selectors
在不使用库的情况下,使用css选择器查找Dom元素的最简单方法是什么?
function select( selector ) {
return [ /* some magic here please :) */ ]
};
select('body')[0] // body;
select('.foo' ) // [div,td,div,a]
select('a[rel=ajax]') // [a,a,a,a]
Run Code Online (Sandbox Code Playgroud)
这个问题纯粹是学术性的.我有兴趣了解这是如何实现的以及"障碍"是什么.这个函数的预期行为是什么?(返回数组,或返回第一个Dom元素等).
mie*_*iek 70
除了自定义hacks之外,在最近的浏览器中,您可以使用W3C Selectors API Level 1中定义的本机方法,即document.querySelector()和document.querySelectorAll():
var cells = document.querySelectorAll("#score > tbody > tr > td:nth-of-type(2)");
Run Code Online (Sandbox Code Playgroud)
如今,在没有图书馆的情况下做这种事情是疯狂的。不过,我假设您想了解这些东西是如何工作的。我建议您查看 jQuery 的源代码或其他 javascript 库之一。
考虑到这一点,选择器函数必须包含大量 if/else/else if 或 switch case 语句,以便处理所有不同的选择器。例子:
function select( selector ) {
if(selector.indexOf('.') > 0) //this might be a css class
return document.getElementsByClassName(selector);
else if(selector.indexOf('#') > 0) // this might be an id
return document.getElementById(selector);
else //this might be a tag name
return document.getElementsByTagName(selector);
//this is not taking all the different cases into account, but you get the idea.
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17658 次 |
| 最近记录: |