jQuery - attr(key, func) 方法



描述

attr(key, func) 方法為所有匹配元素設定單個屬性為計算值。

語法

以下是使用此方法的簡單語法:

selector.attr( key, func )

引數

以下是此方法使用到的所有引數的描述:

  • key - 要設定的屬性名稱。

  • func - 返回要設定的值的函式。此函式將帶有一個引數,該引數是當前元素的索引。

示例

以下示例將為每個表格建立邊框:

<html>
   <head>
      <title>The Selecter Example</title>
      <script type = "text/javascript" 
         src = "https://tutorialspoint.tw/jquery/jquery-3.6.0.js">
      </script>
   
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            $("table").attr("border", function(index) {
               return "4px";
            })
         });
      </script>	
   </head>
	
   <body>
      <table>
         <tr><td>This is first table</td></tr>
      </table>

      <table>
         <tr><td>This is second table</td></tr>
      </table>

      <table>
         <tr><td>This is third table</td></tr>
      </table>	
   </body>
</html>

這將產生以下結果:

jquery-attributes.htm
廣告
© . All rights reserved.