前段時間同事在群組裡對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 embe edobject.
The treatment of attributes with embe edobject. to the W3C HTML5 specification.
複製程式碼
複製程式碼
複製程式碼
複製程式碼
複製程式碼
$("div").data("role") === "page";
$("div").data("lastValue" ) === 43;
$("div").data("hidden") === true;
$("div").data("options").name === "John ";
否則返回字串值
當然文檔裡也特意說明了——如果就是想獲取字符串值而不想得到自動轉換的值,可以使用.attr(“data-” key)來取得對應的值:
複製程式碼
程式碼如下:
To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method.
如下為jQuery
複製程式碼
程式碼如下:
function Attr( elem, key, data data data> nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
// rmultiDash = / 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 = /(?:{[sS]*}|[[sS]*])$/,* / 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; } } return data; } } return data; } } 🎜>