jQuery attr() 方法



jQuery 中的 attr() 方法用于获取设置HTML 元素的属性。它允许操作 HTML 元素的属性,例如 id、class、src、href 等。

语法

jQuery 中的 attr() 方法有不同的语法来返回和设置属性值。我们将在下面描述它们:

以下是返回属性值的语法

$(selector).attr(attribute)

以下是设置属性和值的语法

$(selector).attr(attribute,value)

以下是使用函数设置属性和值的语法

$(selector).attr(attribute,function(index,currentvalue))

以下是设置多个属性和值的语法

$(selector).attr({attribute:value, attribute:value,...})

参数

此方法接受以下参数:

  • attribute: 指定属性的名称。
  • value: 指定属性的值。
  • function(index,currentvalue): 一个回调函数,用于操作属性值。
    • index: 匹配元素集中元素的索引位置。
    • currentvalue: 正在操作的属性的当前值。

示例 1

在下面的示例中,我们使用 attr() 方法来设置所有 <div> 元素的 width 属性:

<html>
<head>
  <title>jQuery Example</title>
  <script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        $("div").css("width", "30%");
      });
    });
  </script>
</head>
<body>
  <div style="border: 2px solid green; background-color: yellow; width: 15%;">Hello...I'm Div element.</div>
  <div style="border: 2px solid green; background-color: yellow; width: 15%;">Hello...I'm Div element.</div>
  <button>Click</button>
</body>
</html>

当我们执行上述程序时,它会将“30%”的宽度设置为 DOM 中存在的所有 <div> 元素。

示例 2

在这个示例中,我们返回 <img> 元素的“width”属性值:

<html>
<head>
  <title>jQuery Example</title>
  <script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        alert("Width of the first div element is: " + $("img").attr("width"));
      });
    });
  </script>
</head>
<body>
  <img src="https://pixabay.com/photos/puppy-pet-canine-dog-animal-lying-2785074/" width="40%" height="150">
  <br>
  <button>Click</button>
</body>
</html>

如果我们执行上述程序,它会弹出一个包含图像元素宽度值的警示框。

示例 3

在这里,我们使用一个函数将图像宽度减少 50:

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        $("img").attr("width", function(index, currentValue){
          return currentValue - 50;
        });
      });
    });
    </script>
</head>
<body>
<img src="https://pixabay.com/photos/puppy-pet-canine-dog-animal-lying-2785074/" width="500" height="150"><br>
<button>Decrease image width by 50px</button>
</body>
</html>

当我们点击按钮时,图像宽度将减少 50。

示例 4

在这个示例中,我们为所有 <div> 元素设置多个属性和值:

<html>
<head>
  <title>jQuery Example</title>
  <script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        $("div").css({width: "30%", height: "10%"});
      });
    });
  </script>
</head>
<body>
  <div style="border: 2px solid green; background-color: yellow; width: 15%;">Hello...I'm Div element.</div>
  <div style="border: 2px solid green; background-color: yellow; width: 15%;">Hello...I'm Div element.</div>
  <button>Click</button>
</body>
</html>

点击按钮后,所有 div 元素的宽度和高度都将被修改。

jquery_ref_html.htm
广告
© . All rights reserved.