1. 程式人生 > >sizzle分析記錄:getAttribute和getAttributeNode

sizzle分析記錄:getAttribute和getAttributeNode

部分IE遊覽器下無法通過getAttribute取值?

<form name="aaron">  
  <input type="text" name="aaron"/>  
</form>
alert(form.getAttribute('name')); IE6、7中錯誤
alert(form.getAttributeNode('name').nodeValue);

看看jQ的解決方案

能力判斷

support.attributes = assert(function( div ) {
    div.className 
= "i"; //設定一個屬性 return !div.getAttribute("className"); });

處理

Sizzle.attr = function( elem, name ) {

    return val !== undefined ?
        val :
        support.attributes || !documentIsHTML ?
            elem.getAttribute( name ) :
            (val = elem.getAttributeNode(name)) && val.specified ?
                val.value :
                
null; };

使用getAttributeNode得到屬性節點,再通過nodeValue得到該屬性節點的值

getAttributeNode的效率比getAttribute要低一些。如果要獲取元素的id,node.id是最快的方法,node.getAttribute('id')其次,getAttributeNode('id').nodeValue最慢。