這裏有一個簡單的例子來說明這個問題:
鑑於這種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的數據對象,當數據改變時,不應該更新屬性嗎?
@James'「div [data-company ='Apple''' - 您忘記關閉']' – 2011-03-31 23:57:57