attr() 方法用來設定或取得被選元素的屬性值。依傳入參數數量不同,它的行為也會跟著改變:只傳屬性名稱時是「取值」,同時傳入名稱與值時則是「賦值」。
按下按鈕後,把圖片的 width 屬性設為 180:
<html>
<head>
<script type="text/javascript" src="https://down.hovertree.com/jquery/jquery-1.12.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("img").attr("width", "180");
});
});
</script>
</head>
<body>
<img src="https://hovertree.comhttps://divcss.yunyiwangluo.com/divcssbuju/UploadFiles_7251/201612/2016122917235040.gif" />
<br />
<button>設置圖像的 width 屬性</button>
</body>
</html>
實際效果:
只傳入屬性名稱,就能把值讀出來,這裡用 alert 顯示圖片寬度:
<html>
<head>
<script type="text/javascript" src="https://down.hovertree.com/jquery/jquery-1.12.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
alert("Image width " + $("img").attr("width"));
});
});
</script>
</head>
<body>
<img src="https://hovertree.com/hvtimg/201506/xlyxp4wg_l.png" width="180" height="140" />
<br />
<button>返回圖像的寬度</button>
</body>
</html>
線上體驗:https://hovertree.com/texiao/jquery/55/
操作 class、id、title 這類一般屬性時,attr() 很合適;但若要處理 checked、disabled、selected 這種會隨使用者互動改變的「狀態」,高版本 jQuery 建議改用 prop(),才不會讀到過時的值。