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