當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


JQuery .attr()用法及代碼示例

獲取匹配元素集中第一個元素的屬性值,或為每個匹配元素設置一個或多個屬性。

用法一

.attr( attributeName ) => String

說明:獲取匹配元素集中第一個元素的屬性值。

  • 添加的版本:1.0.attr( attributeName )

    • attributeName
      類型:String
      要獲取的屬性的名稱。

.attr() 方法僅獲取匹配集中first 元素的屬性值。要單獨獲取每個元素的值,請使用循環構造,例如 jQuery 的 .each().map() 方法。

使用 jQuery 的 .attr() 方法獲取元素屬性的值有兩個主要好處:

  1. 方便:它可以直接在 jQuery 對象上調用並鏈接到其他 jQuery 方法。
  2. 跨瀏覽器一致性:某些屬性的值在不同瀏覽器之間報告不一致,甚至在單個瀏覽器的版本之間。這.attr()方法減少了這種不一致。

注意:屬性值是字符串,除了一些屬性,例如 value 和 tabindex。

從 jQuery 1.6 開始,.attr()方法返回undefined對於尚未設置的屬性。要檢索和更改 DOM 屬性,例如表單元素的 checkedselecteddisabled 狀態,請使用 .prop() 方法。

屬性與屬性

attributesproperties 之間的區別在特定情況下可能很重要。 Before jQuery 1.6.attr() 方法有時會在檢索某些屬性時考慮屬性值,這可能會導致行為不一致。 As of jQuery 1.6.prop() 方法提供了一種顯式檢索屬性值的方法,而 .attr() 檢索屬性。

例如,selectedIndextagNamenodeNamenodeTypeownerDocumentdefaultCheckeddefaultSelected應該使用.prop()方法檢索和設置。在 jQuery 1.6 之前,可以使用 .attr() 方法檢索這些屬性,但這不在 attr 的範圍內。這些沒有對應的屬性,隻是屬性。

關於布爾屬性,考慮由 HTML 標記 <input type="checkbox" checked="checked" /> 定義的 DOM 元素,並假設它位於名為 elem 的 JavaScript 變量中:

elem.checked true(布爾值)將隨複選框狀態而變化
$( elem ).prop( "checked" ) true(布爾值)將隨複選框狀態而變化
elem.getAttribute( "checked" ) "checked" (String) 複選框的初始狀態;不變
$( elem ).attr( "checked" ) (1.6+) "checked" (String) 複選框的初始狀態;不變
$( elem ).attr( "checked" ) (pre-1.6) true(布爾值)隨複選框狀態更改

根據W3C 表格規範, 這checked屬性是一個boolean attribute,這意味著相應的屬性是真的如果該屬性完全存在 - 例如,即使該屬性沒有值或設置為空字符串值,甚至是 "false"。所有布爾屬性都是如此。

然而,關於checked 屬性要記住的最重要的概念是它不對應於checked 屬性。該屬性實際上對應於defaultChecked 屬性,應該隻用於設置複選框的initial 值。 checked 屬性值不會隨複選框的狀態而變化,而 checked 屬性會。因此,cross-browser-compatible 確定是否選中複選框的方法是使用屬性:

  • if ( elem.checked )
  • if ( $( elem ).prop( "checked" ) )
  • if ( $( elem ).is( ":checked" ) )

其他動態屬性也是如此,例如 selectedvalue

其他注意事項:

  • 在版本 9 之前的 Internet Explorer 中,使用 .prop() 將 DOM 元素屬性設置為簡單原始值(數字、字符串或布爾值)以外的任何值,如果不刪除該屬性(使用 .removeProp() )可能會導致內存泄漏在從文檔中刪除 DOM 元素之前。要安全地在 DOM 對象上設置值而不發生內存泄漏,請使用 .data()

例子:

在複選框更改時顯示選中的屬性和屬性。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>attr demo</title>
  <style>
  p {
    margin: 20px 0 0;
  }
  b {
    color: blue;
  }
  </style>
  <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
 
<input id="check1" type="checkbox" checked="checked">
<label for="check1">Check me</label>
<p></p>
 
<script>
$( "input" )
  .change(function() {
    var $input = $( this );
    $( "p" ).html( ".attr( 'checked' ): <b>" + $input.attr( "checked" ) + "</b><br>" +
      ".prop( 'checked' ): <b>" + $input.prop( "checked" ) + "</b><br>" +
      ".is( ':checked' ): <b>" + $input.is( ":checked" ) + "</b>" );
  })
  .change();
</script>
 
</body>
</html>

演示:

找到頁麵中第一個 <em> 的 title 屬性。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>attr demo</title>
  <style>
  em {
    color: blue;
    font-weight: bold;
  }
  div {
    color: red;
  }
  </style>
  <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
 
<p>Once there was a <em title="huge, gigantic">large</em> dinosaur...</p>
 
The title of the emphasis is:<div></div>
 
<script>
var title = $( "em" ).attr( "title" );
$( "div" ).text( title );
</script>
 
</body>
</html>

演示:

用法二

.attr( attributeName, value ) => jQuery

說明:為一組匹配的元素設置一個或多個屬性。

  • 添加的版本:1.0.attr( attributeName, value )

    • attributeName
      類型:String
      要設置的屬性的名稱。
    • value
      類型:StringNumberNull
      為屬性設置的值。如果 null ,指定的屬性將被刪除(如 .removeAttr() )。
  • 添加的版本:1.0.attr( attributes )

    • attributes
      類型:PlainObject
      要設置的attribute-value 對的對象。
  • 添加的版本:1.1.attr( attributeName, function )

    • attributeName
      類型:String
      要設置的屬性的名稱。
    • function
      類型:Function(Integer 索引,String attr)=> StringNumber
      返回要設置的值的函數。 this 是當前元素。接收集合中元素的索引位置和舊屬性值作為參數。

.attr() 方法是設置屬性值的便捷方法,尤其是在設置多個屬性或使用函數返回的值時。考慮下圖:

<img id="greatphoto" src="brush-seller.jpg" alt="brush seller">

設置一個簡單的屬性

要更改 alt 屬性,隻需將屬性名稱及其新值傳遞給 .attr() 方法:

$( "#greatphoto" ).attr( "alt", "Beijing Brush Seller" );

Add 一個屬性同理:

$( "#greatphoto" ).attr( "title", "Photo by Kelly Clark" );

一次設置多個屬性

要同時更改alt 屬性並添加title 屬性,請使用純JavaScript 對象一次將兩組名稱和值傳遞給方法。對象中的每個鍵值對添加或修改一個屬性:

$( "#greatphoto" ).attr({
  alt: "Beijing Brush Seller",
  title: "photo by Kelly Clark"
});

設置多個屬性時,屬性名稱周圍的引號是可選的。

警告:設置'class' 屬性時,必須始終使用引號!

注意:試圖改變type一個屬性input或者button通過創建的元素document.createElement()將在 Internet Explorer 8 或更早版本上引發異常。

計算的屬性值

通過使用函數設置屬性,您可以根據元素的其他屬性計算值。例如,要將新值與現有值連接:

$( "#greatphoto" ).attr( "title", function( i, val ) {
  return val + " - photo by Kelly Clark";
});

當一次修改多個元素的屬性時,使用函數計算屬性值特別有用。

注意:如果在 setter 函數中沒有返回任何內容(即。function(index, attr){}), 或者如果undefined返回時,當前值不變。這對於僅在滿足某些條件時有選擇地設置值很有用。

例子:

為頁麵中的所有 <img> 設置一些屬性。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>attr demo</title>
  <style>
  img {
    padding: 10px;
  }
  div {
    color: red;
    font-size: 24px;
  }
  </style>
  <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
 
<img>
<img>
<img>
 
<div><b>Attribute of Ajax</b></div>
 
<script>
$( "img" ).attr({
  src: "/wp-content/uploads/2022/05/jquery-demos/hat.gif",
  title: "jQuery",
  alt: "jQuery Logo"
});
$( "div" ).text( $( "img" ).attr( "alt" ) );
</script>
 
</body>
</html>

演示:

根據頁麵中的位置設置 div 的 id。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>attr demo</title>
  <style>
  div {
    color: blue;
  }
  span {
    color: red;
  }
  b {
    font-weight: bolder;
  }
  </style>
  <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
 
<div>Zero-th <span></span></div>
<div>First <span></span></div>
<div>Second <span></span></div>
 
<script>
$( "div" )
  .attr( "id", function( arr ) {
    return "div-id" + arr;
  })
  .each(function() {
    $( "span", this ).html( "(id = '<b>" + this.id + "</b>')" );
});
</script>
 
</body>
</html>

演示:

從圖像上的標題屬性設置 src 屬性。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>attr demo</title>
  <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
 
<img title="hat.gif">
 
<script>
$( "img" ).attr( "src", function() {
  return "/wp-content/uploads/2022/05/jquery-demos/" + this.title;
});
</script>
 
</body>
</html>

演示:

相關用法


注:本文由純淨天空篩選整理自jquery.com大神的英文原創作品 .attr()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。