jQuery 雜項 removeData() 方法



jQuery 的 removeData() 方法用於移除之前使用 data() 方法設定的資料。

語法

$(selector).removeData(name)

引數

以下是上述語法的描述 -

  • name (可選): 要移除的資料的名稱。如果省略,則會移除與元素關聯的所有資料。

示例

在下面的示例中,我們使用 jQuery 雜項 removeData() 方法從 <div> 元素中移除之前附加的資料 -

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#saveData").click(function(){
    $("#info").data("username", "Tutorialspoint");
    alert("Username saved: " + $("#info").data("username"));
  });
  
  $("#clearData").click(function(){
    $("#info").removeData("username");
    alert("Username after removal: " + $("#info").data("username"));
  });
});
</script>
</head>
<body>
<button id="saveData">Save Username</button><br>
<button id="clearData">Clear Username</button>
<p id="info"></p>
</body>
</html>

執行後,點選上面的“儲存”和“清除”按鈕。

jquery_ref_miscellaneous.htm
廣告

© . All rights reserved.