attr()方法獲取或設(shè)置所選元素的屬性和值。
當(dāng)attr()方法用于獲取屬性值時(shí),它將返回第一個(gè)選定元素的值。
當(dāng)attr()方法用于設(shè)置屬性值時(shí),它將為所有選定元素設(shè)置一個(gè)或多個(gè)屬性/值對。
要?jiǎng)h除屬性,請改用removeAttr()方法。
獲取屬性的值:
$(selector).attr(attribute)
設(shè)置屬性和值:
$(selector).attr(attribute, value)
設(shè)置多個(gè)屬性和值:
$(selector).attr({attribute:value, attribute:value, ...})使用函數(shù)設(shè)置屬性和值
$(selector).attr(attribute, function(index, currentValue))
獲取圖像的src屬性值:
$("button").click(function(){
$("img").attr("src");
});測試看看?/?設(shè)置圖像的src屬性:
$("button").click(function(){
$("img").attr("src", "icon_jquery.png");
});測試看看?/?設(shè)置多個(gè)屬性和值:
$("button").click(function(){
$("img").attr({
alt: "Parrot Icon",
title: "Image by Seagull",
width: "350px",
height: "300px"
});
});測試看看?/?使用函數(shù)設(shè)置屬性和值:
$("button").click(function(){
$("img").attr("width", function(i, val){
return val - 60;
});
});測試看看?/?從下拉列表中設(shè)置src屬性的值:
| 參數(shù) | 描述 |
|---|---|
| attribute | 指定屬性名稱 |
| value | 指定屬性的值 |
| function(index, currentValue) | 指定一個(gè)函數(shù),該函數(shù)返回要設(shè)置的屬性值
|