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.com/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.