jQuery data() 及其示例


jQuery 中的 data() 方法用於附加資料或從選定的元素獲取資料。

語法

語法如下 −

$(selector).data(name)
$(selector).data(name,value)

其中,對於第 1 個語法,name 是要檢索的資料的名稱。

對於第 2 個語法,name 是要設定的資料的名稱,而 value 是要設定的資料的值。

示例

現在讓我們看一個實現 jQuery **data() 方法** 的示例−

 線上試用

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $(".button1").click(function(){
         $("div").data("student", "Jack Sparrow");
         alert("Student Name = " +$("div").data("student"));
      });
      $(".button2").click(function(){
         $("div").removeData("student");
         alert("Student Name = " +$("div").data("Jack Sparrow"));
      });
   });
</script>
<style>
.button1 {
   background-color: orange;
   color: white;
}
.button2 {
   background-color: orange;
   color: white;
}
</style>
</head>
<body>
<h2>Demo Heading</h2>
<button class="button1">Attach</button><br><br>
<button class="button2">Remove</button>
<div></div>
</body>
</html>

輸出

這將產生以下輸出 −

更新於: 31-Dec-2019

553 次瀏覽

開啟你的 職業生涯

完成課程以進行認證

開始使用
廣告
© . All rights reserved.