国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

jQuery $.data()方法使用注意細節

2024-05-06 14:20:12
字體:
來源:轉載
供稿:網友
前段時間同事在群里對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;
若值是純數字構成的字符串(+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;
}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 大竹县| 花莲市| 开鲁县| 瑞金市| 大关县| 两当县| 黑龙江省| 喀喇| 常熟市| 佳木斯市| 华亭县| 蓬溪县| 新源县| 榆中县| 宜春市| 汉阴县| 寿宁县| 芒康县| 乌兰浩特市| 张家口市| 忻城县| 曲水县| 海宁市| 丰顺县| 花莲市| 雷山县| 札达县| 济源市| 依安县| 滦南县| 香格里拉县| 姚安县| 孝昌县| 铜梁县| 五寨县| 南溪县| 临高县| 玛多县| 千阳县| 鄢陵县| 德阳市|