jQuery attr()メソッド
例
画像の幅属性を設定します。
$("button").click(function(){
$("img").attr("width","500");
});
定義と使用法
attr()メソッドは、選択した要素の属性と値を設定または返します。
このメソッドを使用して属性値を返す場合、最初に一致した要素の値を返します。
このメソッドを使用して属性値を設定すると、一致した要素のセットに対して1つ以上の属性/値のペアが設定されます。
構文
属性の値を返します。
$(selector).attr(attribute)
属性と値を設定します。
$(selector).attr(attribute,value)
関数を使用して属性と値を設定します。
$(selector).attr(attribute,function(index,currentvalue))
複数の属性と値を設定します。
$(selector).attr({attribute:value, attribute:value,...})
Parameter | Description |
---|---|
attribute | Specifies the name of the attribute |
value | Specifies the value of the attribute |
function(index,currentvalue) | Specifies a function that returns the attribute value to set
|
自分で試してみてください-例
を返す要素の属性の値を返す方法。
設定する関数を使用して要素の属性値を設定する方法。
を設定する要素に複数の属性/値を設定する方法。