2011-03-31 22 views
32

這裏有一個簡單的例子來說明這個問題:

鑑於這種HTML標記:

<div data-company="Microsoft"></div> 

這jQuery代碼(使用jQuery 1.5.1):

// read the data 
alert($("div").data("company")); 
// returns Microsoft <<< OK! 

// set the data 
$("div").data("company","Apple"); 
alert($("div").data("company")); 
// returns Apple <<< OK! 

// attribute selector 
alert($("div[data-company='Apple']").length); 
// returns 0 <<< WHY??? 

// attribute selector again 
alert($("div[data-company='Microsoft']").length); 
// returns 1 <<< WHY??? 

// set the attribute directly 
$("div").attr("data-company","Apple"); 
alert($("div[data-company='Apple']").length); 
// now returns 1 <<< OK! 

因爲jQuery的自動進口將HTML5 data- *轉換爲jQuery的數據對象,當數據改變時,不應該更新屬性嗎?

+1

@James'「div [data-company ='Apple''' - 您忘記關閉']' – 2011-03-31 23:57:57

回答

51

通常情況下,有沒有需要雙向傳遞.data()的,如果你在使用。數據是一致的()來訪問/設置/修改DOM元素的數據。因此,爲每個.data()設置/修改操作(.data()在內部將其值存儲在jQuery.cache中)避免訪問DOM的性能開銷是有意義的。

如果要自己強制執行往返行爲,可以訂閱「setData」或「changeData」事件,然後通過.attr()將這些事件中的更新推送到相應的DOM元素。

+2

這很有道理 - 那麼在選擇器的上下文中使用.data()的首選方法是什麼?假設我想訪問使用.data()設置/修改的data-company ='Microsoft'的所有元素? – 2011-04-01 00:12:10

+1

我不認爲有一種簡單的方法來查詢'.data()'緩存。如果你想使用這樣的選擇器,你需要在我提到的「changeData」事件上實現往返。然後,你可以保持你的數據屬性與'.data()'改變同步(你也可以選擇性地對待你想要查詢的元素)。 – 2011-04-01 00:19:50

+0

謝謝戴夫!順便說一句,我喜歡你的tekpub系列。 – 2011-04-01 00:38:51

16

這是根據該文檔正確的行爲:

Data-用屬性被拉到在第一時間中的數據屬性被訪問,然後不再訪問或突變的(所有的數據值然後被存儲內部在jQuery中)。

(來源:http://api.jquery.com/data

+0

這是否一直是這種情況,或者是其中一個版本發生了變化? – 2012-11-19 14:41:10

+1

看起來情況一直如此。上述文檔的引用也在1.4.3的發行說明中,當此功能首次發佈時:http://blog.jquery.com/2010/10/16/jquery-143-released/ – Craig 2013-11-25 19:16:52

相關問題