在dom操作时,有时根据id获取单个对象、有时根据className获取多个对象。平常可能我们用两个函数来实现这两个功能。不过我将它们整合了一下,目前使用情况良好,函数如下:
03 | 
function $(selector, tag, parent) { | 
 
07 | 
    if (!selector) { return null; } | 
 
10 | 
    if (selector.nodeType) { | 
 
11 | 
        return selector.nodeType == 3 ? null : selector; | 
 
16 | 
    if (selector.length && selector.constructor != String) { | 
 
17 | 
        ret = Array.prototype.slice.call(selector, 0, selector.length); | 
 
19 | 
        for(var i=0; i < ret.length; i++) { | 
 
20 | 
            if (!ret[i].nodeType || ret[i].nodeType == 3) { ret.splice(i,1); i--; } | 
 
21 | 
            else if (tag && ret[i].tagName.toLowerCase() != tag.toLowerCase()) { | 
 
30 | 
    if (selector.constructor == String) { | 
 
32 | 
        if (/^\.\w+/.test(selector)) { | 
 
33 | 
            parent = parent || document; | 
 
35 | 
            nodes = parent.getElementsByTagName(tag); | 
 
36 | 
            var className = selector.replace(".", ""); | 
 
37 | 
            var reg = new RegExp("(^|\\b)" + className + "(\\b|$)"); | 
 
38 | 
            for(var i=0; i < nodes.length; i++) { | 
 
39 | 
                if(reg.test(nodes[i].className)) { ret.push(nodes[i]); } | 
 
44 | 
        return document.getElementById(selector); | 
 
 
 
下面它的使用方法,为了配合演示,请先准备如下HTML结合代码:
02 | 
    <p class="t">Hello,world!</p> | 
 
04 | 
    <li class="t">afasdfsa</li> | 
 
06 | 
    <li class="t">sdklfajsfjk</li> | 
 
11 | 
    <li class="t">附加的第一项</li> | 
 
12 | 
    <li class="t">附加的第二项</li> | 
 
13 | 
    <li class="t">附加的第三项</li> | 
 
 
 
上面的代码结构只是为测试而写的,所以比较的另类……勿怪!!!
返回到$函数,它具有如下一些功能:
- $() : 返回null;
 
- $("id") :返回单个对象,如下:alert ( $("test") );  // object HTMLUListElement
 
- $(".t") :返回所有className为t的元素组成的数组,如下:alert ( $(".t").length );  //7,共有7个元素的className为t,有木有?
 
- $(".t", 'li') :返回className为t的li标签对象,如下:alert ( $(".t", 'li').length );  // 6,有一个<p>的类样式也是t,但是被排除了
 
- $(".t", "li", $("test")):返回ID为test的元素下的<li>且类样式为t的对象,如下:alert ( $(".t", 'li', $("test")).length );   // 3,范围在test之内
 
- $($("test").childNodes) : 将test的子元素组合成一个数组,并过滤掉文本节点,如下:alert ( $($("test").childNodes).length );  //共7个
 
- $($("test").childNodes, 'p') : 获取test的子元素中为<p>的那些元素,如下:alert ( $($("test").childNodes, 'p').length );  // 2,刚好两个<p>
 
- 还可以传递一个数组,如下:
 
1 | 
var arr = [1,2,3,document, document.body]; | 
 
2 | 
alert ( $(arr).length );   | 
 
 
 
另外,$与$结合使用的话,就会更加的方便了。以上只是我个人在使用的一个函数,仅供参考。