前段时间同事在群里对jquery里的.data()方法大发牢骚,接下来介绍jquery $.data()方法使用注意细节,需要了解的朋友可以参考下
前段时间同事在群里对jquery里的.data()方法大发牢骚:
xxx(nnnnnnn) 15:11:34
04c56742643469ab65b61174e724dc34
alert($('#a').data('xxx'));//123
data方法不靠谱
xxx(nnnnnnn) 15:13:17
老老实实用attr('data-xxx')吧细研究了下jquery文档对.data()方法的描述:
as of jquery 1.4.3 html 5 data- attributes will be automatically pulled in to jquery's data object.
the treatment of attributes with embedded dashes was changed in jquery 1.6 to conform to the w3c html5
specification.
针对如下示便:
<p data-role="page" data-last-value="43" data-hidden="true" data-options='{"name":"john"}'></p>
$("p").data("role") === "page";
$("p").data("lastvalue") === 43;
$("p").data("hidden") === true;
$("p").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)来获取相应的值:
to retrieve the value's attribute as a string without any attempt to convert it, use the attr() method.
如下为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;
}
以上就是总结jquery中$.data()用法注意事项的详细内容。