2011年12月22日星期四

getElementsByAttribute

//属性选择符
//author:司徒正美 ref:http://www.cnblogs.com/rubylouvre/archive/2009/10/26/1590102.html
//正则支持 tag[attrName ^\$\*\~\!=attrValue]
var getElementsByAttribute = function(search) {
    var tag = /([\*a-zA-Z1-6]*)?(\[(\w+)\s*(\^|\$|\*|\||~|!)?=?\s*([\w\u00C0-\uFFFF\s\-_\.]+)?\])?/,
            node = arguments[1] || document,
            agent = search.match(tag),
            tag = agent[1] || "*",  //html标签
            attribute = agent[3],  //属性名
            type = agent[4] + "=", //比较符号 ^ $ * | ~ !
            value = agent[5],//属性值
            ieAttrFix = {"class": "className","for": "htmlFor"},  //特殊属性名
            returnElements = [],
        //IE5.5不支持“*”
            elements = (tag === "*" && node.all) ? node.all : node.getElementsByTagName(tag),
            length = elements.length;
    if ((!!document.querySelectorAll) && type != "!=") {//ie8+ 标准browser
        elements = document.querySelectorAll(search);
        for (var i = 0,length = elements.length; i < length; i++) {
            returnElements.push(elements[i]);
        }
        return returnElements
    }
    if (!+"\v1")  //ie检测
        attribute = ieAttrFix[attribute] ? ieAttrFix[attribute] : attribute;
    while (length--) {
        var current = elements[length],
                _value = !+"\v1" ? current[attribute] : current.getAttribute(attribute);
        if (typeof _value === "string" && _value.length > 0) {
            if (!!value) {
                var condition =
                        type === "=" ? //完全等于
                                _value === value :
                                type === "!=" ? //不等于
                                        _value != value :
                                        type === "*=" ? //包含
                                                _value.indexOf(value) >= 0 :
                                                type === "~=" ? //匹配当中的某个单词,如警告
                                                        (" " + _value + " ").indexOf(value) >= 0 :
                                                        type === "^=" ? //以XX开头
                                                                _value.indexOf(value) === 0 :
                                                                type === "$=" ? //以XX结尾
                                                                        _value.slice(-value.length) === value :
                                                                        type === "|=" ? //匹配属性值为XX或以XX-打头的元素
                                                                                _value === value || _value.substring(0, value.length + 1) === value + "-" :
                                                                                false;
                condition && returnElements.push(current);
            } else {
                returnElements.push(current)
            }
        }
    }
    return returnElements;
}

没有评论:

发表评论