DIV CSS 佈局教程網

動手學 jQuery:attr() 屬性讀取與設定
編輯:JQuery特效代碼     

定義與用法

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(),才不會讀到過時的值。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved