跳转到主内容
新派编程网 - 新潮编程理念,全新技术课堂!

总结jQuery中$.data()用法注意事项

前段时间同事在群里对 jquery 里的.data()方法大发牢骚,接下来介绍 jquery $.data()方法使用注意细节,需要了解的朋友可以参考下 前段时间同事在群里对jQuery里的.data()方法大发牢骚: XXX(NNNNNNN) 15:11:34 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"; $("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)来获取相应的值: 基于jQuery的AJAX和JSON的实例 中文WORD版 本文档主要讲述的是基于jQuery的AJAX和JSON的实例;过jQuery内置的AJAX功能,直接访问后台获得JSON格式的数据,然后通过jQuer把数据绑定到事先设计好的html模板上,直接在页面上显示。有需要的朋友可以下载看看 下载
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; }

相关文章