首頁  >  屬性  > attr(name|pro|key,val|fn)

返回值:Stringattr(name|properties|key,value|fn)

jQuery attr() 方法概述

設(shè)置或返回被選元素的屬性值。

參數(shù)

nameStringV1.0

屬性名稱

propertiesMapV1.0

作為屬性的“名/值對”對象

key,valueString,ObjectV1.0

屬性名稱,屬性值

key,function(index, attr)String,FunctionV1.1

1:屬性名稱。

2:返回屬性值的函數(shù),第一個參數(shù)為當(dāng)前元素的索引值,第二個參數(shù)為原先的屬性值。

示例

參數(shù)name 描述:

返回文檔中所有圖像的src屬性值。

jQuery 代碼:
$("img").attr("src");

參數(shù)properties 描述:

為所有圖像設(shè)置src和alt屬性。

jQuery 代碼:
$("img").attr({ src: "test.jpg", alt: "Test Image" });

參數(shù)key,value 描述:

為所有圖像設(shè)置src屬性。

jQuery 代碼:
$("img").attr("src","test.jpg");

參數(shù)key,回調(diào)函數(shù) 描述:

把src屬性的值設(shè)置為title屬性的值。

jQuery 代碼:
$("img").attr("title", function() { return this.src });