data()方法將任意數(shù)據(jù)存儲(chǔ)到選定元素或從中獲取數(shù)據(jù)。
當(dāng)使用data()方法獲取數(shù)據(jù)時(shí),它將返回第一個(gè)選定元素的數(shù)據(jù)。
當(dāng)data()方法用于存儲(chǔ)數(shù)據(jù)時(shí),它將數(shù)據(jù)存儲(chǔ)到所有選定的元素。
要?jiǎng)h除數(shù)據(jù),請(qǐng)使用removeData()方法。
返回所選元素的存儲(chǔ)數(shù)據(jù):
$(selector).data(key)
將數(shù)據(jù)存儲(chǔ)到選定的元素:
$(selector).data(key, value)
使用對(duì)象將數(shù)據(jù)存儲(chǔ)到選定的元素:
$(selector).data(key, object)
從第一個(gè)列表項(xiàng)中檢索數(shù)據(jù):
$("#btn1").click(function(){
alert($("li").data("price"));
});測(cè)試看看?/?將數(shù)據(jù)存儲(chǔ)到DIV元素,然后檢索數(shù)據(jù):
// 存儲(chǔ)數(shù)據(jù)
$("#btn1").click(function(){
$("div").data("msg", "Hello World");
});
// 獲取數(shù)據(jù)
$("#btn2").click(function(){
$("div").text($("div").data("msg"));
});測(cè)試看看?/?使用對(duì)象將數(shù)據(jù)存儲(chǔ)到DIV元素,然后檢索數(shù)據(jù):
$("button").click(function(){
$("div").data("test", {first: 16, last: "pizza!"});
$("span:first").text($("div").data("test").first);
$("span:last").text($("div").data("test").last);
});測(cè)試看看?/?通過按鈕檢索“數(shù)據(jù)視頻”屬性:
$("#videoModal").on("show.bs.modal", function(event) {
let button = $(event.relatedTarget); // 觸發(fā)模態(tài)的按鈕
let url = button.data("video"); // 從數(shù)據(jù)-視頻屬性中提取url
$(this).find("iframe").attr({
src : url,
allow : "accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
});
});測(cè)試看看?/?| 參數(shù) | 描述 |
|---|---|
| key | 指定要設(shè)置的數(shù)據(jù)的鍵(名稱) |
| value | 指定要設(shè)置的數(shù)據(jù)值 |
| object | 鍵值對(duì)數(shù)據(jù)對(duì)象要更新 |