jQuery prop() 方法



jQuery 中的 prop() 方法用於獲取設定DOM 中元素的屬性。

如果您嘗試使用此方法獲取屬性值,它會為您提供與您的選擇匹配的第一個元素的屬性值。但是,如果您嘗試設定屬性值,它會將與您的選擇匹配的所有元素的屬性更改為您指定的屬性值。

如果我們想刪除一個屬性,我們需要使用removeProp()方法。

語法

我們有不同的語法來設定和獲取所選元素的屬性和值 -

以下是獲取屬性值的語法

$(selector).prop(property)

以下是設定屬性和值的語法

$(selector).prop(property,value)

以下是使用函式設定屬性和值的語法

$(selector).prop(property,function(index,currentvalue))

以下是設定多個屬性和值的語法

$(selector).prop({property:value, property:value,...})

引數

此方法接受以下引數 -

  • property: 您要獲取或設定的屬性的名稱。
  • value: 您要為屬性設定的值。
  • function(index, currentvalue): 這是一個將在每個選定元素上執行的回撥函式。它接收兩個引數
    • index: 選定元素集中當前元素的索引。
    • currentvalue: 當前元素正在操作的屬性的當前值。

示例 1

在下面的示例中,我們使用 prop() 方法來獲取<input> 元素的屬性值 -

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function() {
        $('button').click(function() {
            var isChecked = $('#myCheckbox').prop('checked');
            alert('Checkbox is ' + (isChecked ? 'checked' : 'unchecked'));
        });
    });
  </script>
</head>
<body>
    <input type="checkbox" id="myCheckbox" checked>
    <button>Check Status</button>
    <p id="status"></p>
</body>
</html>

當我們點選按鈕時,prop() 將獲取複選框的狀態(選中或未選中)並在警報框中顯示它。

示例 2

在這個示例中,我們設定了<input> 元素的屬性值 -

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
      $(document).ready(function() {
          $('button').click(function() {
              $('#myCheckbox').prop('checked', true);
          });
      });
  </script>
</head>
<body>
    <input type="checkbox" id="myCheckbox">
    <button>Check Checkbox</button>
</body>
</html>

執行上述程式後,它將複選框的 checked 屬性顯示為“true”。

示例 3

在下面的示例中,我們使用帶函式引數的 prop() 方法 -

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
      $(document).ready(function() {
          $('button').click(function() {
              $('.checkItem').prop('checked', function(index, currentValue) {
                  return !currentValue;
              });
          });
      });
  </script>
</head>
<body>
    <input type="checkbox" class="checkItem">
    <input type="checkbox" class="checkItem">
    <input type="checkbox" class="checkItem">
    <button>Toggle Checkboxes</button>
</body>
</html>

這裡,prop() 與函式一起使用,在點選按鈕時切換多個複選框的 checked 屬性。

示例 4

此示例將多個屬性(disabled 和 innerHTML)設定到按鈕元素 -

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function() {
      $('#disableButton').click(function() {
          $('#myButton').prop({
              disabled: true,
              innerHTML: 'Disabled'
          });
      });
  });
</script>
</head>
<body>
    <button id="myButton">Click Me!</button>
    <button id="disableButton">Disable the Button Above</button>
</body>
</html>

當您點選一個按鈕時,它會更改它旁邊的按鈕。被點選的按鈕將被停用,這意味著您無法再點選它,並且它的文字也會發生變化。

jquery_ref_html.htm
廣告

© . All rights reserved.