json的引號之傷

來源:互聯網
上載者:User

標籤:

最近讀他們的jquery解讀的源碼,由於版本不同,我可能看的是他們解讀的1.7的,但是我本身啟動並執行可能是1.9的,所以有些出處,但是中心思想不變,我有疑問的時候,直接debug,讓例子自己走一遍,好處是一目瞭然,缺點就是有些分支走不到,近我的可能吧!能理解的理解,理解不了的實踐;這個是目前我的基本思路;

這幾天在解讀$.data(),$("").data()方法,之後會單獨拿出文章來寫自己的心得體會,看源碼-》看一些前輩大神們的源碼解讀-》自己實踐-》自己總結體會,扯遠了

看到一篇文章寫的是html5的屬性data-xx的,即使咱們現在瀏覽器不支援html5,但是用jquery的話依然可以使用這些方法,舉例說明(摘自網上):

<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在這裡用到的主要方法說一下:

//elem代表div,key代表我們的role、lastValue等,data=undefined
function dataAttr( elem, key, data ) {// If nothing was found internally, try to fetch any// data from the HTML5 data-* attribute
     //這裡主要工作就是解析“data-“形式的屬性,判斷data是否未定義,並且節點是不是element元素
     //如果data有值,則直接返回,因為在調用這個方法之前還有其他的方法調用,可能已經把data計算出來了if ( data === undefined && elem.nodeType === 1 ) {         //組裝name屬性,例如name = "data-role"var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();         //js的原生代碼得到data的值data = elem.getAttribute( name );         //是否是string類型if ( typeof data === "string" ) {try {
                  //各種判斷,boolean,null,數字,stringdata = data === "true" ? true :data === "false" ? false :data === "null" ? null :// Only convert to a number if it doesn‘t change the string
                       //這裡有個技巧:這個”+“可以用來判斷數字,它先強制把對象轉化成數字,如果對象本身不是數字,則返回NaN,例如:+5==5(true),+‘a‘==‘a‘(false)+data + "" === data ? +data :
                        //測試資料是否是以{}包裹,是則嘗試轉成對象,這裡提一下jQuery.paseJSON()這個方法,它會按照json的定義去判斷參數,然後返回對象,不符合的轉換不了,返回undefinedrbrace.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;}

我這裡說一下json對象,裡面的屬性必須是雙引號,不能使用單引號,雖然頁面界別不怎麼區分,但是在json解析的時候會報錯,例如

<div data-role="page" data-last-value="43" data-hidden="true" data-options=‘{"name":"John"}‘></div> ,

cache中的儲存是一個obj{name:"John"};

data-options的內容引號互換

<div data-role="page" data-last-value="43" data-hidden="true" data-options="{‘name‘:‘John‘}"></div>

 $("div").data("options").name === "undefined";

cache中的儲存是一個字串:"{‘name‘:‘John‘}"

關於cache的相關知識同樣在執行個體和靜態方法data中會講解

 

json的引號之傷

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.