data-* 屬性用于存儲私有頁面后應用的自定義數據。
data-* 屬性可以在所有的 HTML 元素中嵌入數據。
自定義的數據可以讓頁面擁有更好的交互體驗(不需要使用 Ajax 或去服務端查詢數據)。
data-* 屬性由以下兩部分組成:
1. 屬性名不要包含大寫字母,在 data- 后必須至少有一個字符。
2. 該屬性可以是任何字符串
<!DOCTYPE html>
<html>
<head><meta charset="utf-8" /><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script><title></title>
</head>
<body><div id="testDiv" data-cname="張三" data-e-name="zhangsan" data-user-id="123456">111111111</div><div id="test" data-age="24">Click Here</div><div id="example" data-info="hello">這是一個示例</div><div id="example2" data-custom-attribute="value">這是一個示例example2</div><br /><div><input id='chkTest' type="checkbox" data-fun-description="同意" />同意協議<input id="saveBtn" type="button" value="保存" /></div><script type="text/javascript">$(document).ready(function () {//JavaScriptvar userId = document.querySelector('div').dataset.userId;console.log("Ln 25:" + userId); // 輸出: 123456var usercname = document.getElementById('testDiv').getAttribute('data-cname');console.log("Ln 28:" + usercname); // 輸出: 張三var el = document.getElementById("testDiv");console.log("Ln 31:" + el.dataset.cname);//輸出: 張三el.dataset.cname = "ZS";//設置值為"ZS"console.log("Ln 33:" + el.dataset.cname);//輸出: ZS//jQueryvar info = $('#example').data('info');console.log("Ln 37:" + info); // 輸出: hellovar infoAttr = $('#example').attr('data-info');// 直接獲取原始字符串值console.log("Ln 40:" + infoAttr); // 輸出: hello$('#example').data('info', 'world');var updatedInfo = $('#example').data('info');console.log("Ln 44 修改內容:" + updatedInfo); // 輸出: worldvar value = $('#example2').data('customAttribute'); // 注意:駝峰命名法轉換規則(camelCase)console.log("Ln 47:" + value); // 輸出:value$('#example').data('customAttribute', 'newValue'); // 設置值var updatedValue = $('#example').data('customAttribute'); // 讀取值console.log("Ln 52 修改內容:" + updatedValue); // 輸出:newValue//復選框 prop 選中狀態$('#saveBtn').click(function () {if ($('input[type="checkbox"]:checked[data-fun-description="同意"]').prop('checked')) {console.log("Ln 57:選中");} else {console.log("Ln 57:未選中");}});console.log("Ln 63 刪除testDiv元素上 ename 鍵/值對。");$("#testDiv").removeData("ename");});</script>
</body>
</html>
*
*
*
*
*