JQuery源码解读__5__数据缓存data()

345 阅读1分钟

JQ的data( 妙味讲堂 - 视频笔记 - 第六部分)

1、attr()方法

//jquery实现
$("div").attr("name", "hello");
console.log($("div").attr("name")); //hello

//原生实现
document.getElementsById("div").setAttribute("name","hello");
let name  = document.getElementsById("div").getAttribute("name");
console.log(name);// hello

2、prop()方法

//jquery实现
$("div").prop("name", "hello");console.log($("div").prop("name")); //hello// j原生实现
document.getElementsById("div")["name"] = "hello"document.getElementsById("div").getAttribute("name");
let name  = document.getElementsById("div").getAttribute("name");
console.log(name);// hello

3、jquery实现的数据缓存

//data设置获取数据
$("div").data("name", "hello");
console.log($("div").data("name")); //hello

// DOM节点设置好的数据
<div data-index='1' id='box'>1</div>
console.log($("#box").data(index));//1

4、源码实现:

data: function( key, value ) { 
   var attrs, name,   
     data = null,    
    i = 0,      
  elem = this[0];     
  // 不传参数就获取所有data数据
  if ( key === undefined ) {  
      if ( this.length ) {    
        data = jQuery.data( elem );    
        if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {  
              attrs = elem.attributes;       
         for ( ; i < attrs.length; i++ ) {     
               name = attrs[i].name;    
                if ( name.indexOf("data-") === 0 ) {    
                    name = jQuery.camelCase( name.slice(5) );     
                   dataAttr( elem, name, data[ name ] );      
              }        
        }      
          jQuery._data( elem, "parsedAttrs", true );   
         }      
  }     
   return data;  
  }   
 // 设置多个值
    if ( typeof key === "object" ) {   
     return this.each(function() {    
        jQuery.data( this, key );   
     });  
  }  
  return arguments.length > 1 ? 
       //设置单个值
    this.each(function() {    
        jQuery.data( this, key, value );   
     }) :   
     //获取单个值 
     elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null;
}

function dataAttr( elem, key, data ) { 
   // If nothing was found internally, try to fetch any  
  // data from the HTML5 data-* attribute 
   if ( data === undefined && elem.nodeType === 1 ) { 
       var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();    
    data = elem.getAttribute( name );    
    if ( typeof data === "string" ) {      
      try {              
  data = data === "true" ? true :  
                  data === "false" ? false :      
              data === "null" ? null :    
                // Only convert to a number if it doesn't change the string      
              +data + "" === data ? +data :    
                rbrace.test( data ) ? jQuery.parseJSON( data ) :    
                    data;         
   } catch( e ) {}    
        // Make sure we set the data so it isn't changed later   
         jQuery.data( elem, key, data );    
    } else {       
     data = undefined;   
     }   
 } 
   return data;
}