jQuery$.data()⽅法使⽤注意细节
前段时间同事在⾥对jQuery⾥的.data()⽅法⼤发牢骚:
XXX(NNNNNNN) 15:11:34
<a id="a" data-xxx="00123" />
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.
复制代码代码如下:
<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;
jquery字符串截取
若值是纯数字构成的字符串(+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 && deType === 1 ) {
// rmultiDash = /([A-Z])/g
var name = "data-" + place( rmultiDash, "-$1" ).toLowerCase();
data = Attribute( 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]*\])$/,*/
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;
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。