jQueryその他のdata()メソッド

❮jQueryその他のメソッド

<div>要素にデータを添付してから、データを取得します。

$("#btn1").click(function(){
  $("div").data("greeting", "Hello World");
});
$("#btn2").click(function(){
  alert($("div").data("greeting"));
});

定義と使用法

data()メソッドは、選択した要素にデータを添付したり、選択した要素からデータを取得したりします。

ヒント:データを削除するには、removeData()メソッドを使用します。


要素からデータを返す

選択した要素から添付データを返します。

構文

$(selector).data(name)

Parameter Description
name Optional. Specifies the name of data to retrieve.
If no name is specified, this method will return all stored data for the element as an object


要素にデータを添付する

選択した要素にデータを添付します。

構文

$(selector).data(name,value)

Parameter Description
name Required. Specifies the name of data to set
value Required. Specifies the value of data to set

オブジェクトを使用して要素にデータをアタッチする

名前と値のペアを持つオブジェクトを使用して、選択した要素にデータを添付します。

構文

$(selector).data(object)

Parameter Description
object Required. Specifies an object containing name/value pairs

❮jQueryその他のメソッド