jQuery $.data()方法使用注意细节

示例如下: 

<div data-role="page" data-last-value="43" data-hidden="true" data-options='{"name":"John"}'></div> 
$("div").data("role") === "page"; 
$("div").data("lastValue") === 43; 
$("div").data("hidden") === true; 
$("div").data("options").name === "John";

即当使用.data()获取值时,jQuery会首先尝试将获取的字符串值转化成JS类型,包括布尔值,null,数字,对象,数组:
若值是”true|false”,则返回相应的布尔值;
若值是”null”,则返回null;
若值是纯数字构成的字符串(+data + ”” === data),则返回相应的数字(+data);
若值是由(?:\{[\s\S]*\}|\[[\s\S]*\])$,比如”{key:value}“或[1,2,3],则尝试使用jQuery.parseJSON解析之;
 
否则返回字符串值
如果就是想获取字符串值而不想获得自动转换的值,可以使用.attr(“data-”+key)来获取相应的值:

下为jQuery源码 
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 ) { 
// rmultiDash = /([A-Z])/g 
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); 
data = elem.getAttribute( name ); 
if ( typeof data === "string" ) { 
try { 
/*.data(key)方法尝试将获取的值转化成JS类型,包括布尔值,null,数字,对象,数组*/ 
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 = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,*/ 
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; 
} 

 

posted @ 2016-06-02 14:26  慕容小凡  阅读(770)  评论(2)    收藏  举报