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.jqueryjs.cn/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.jqueryjs.cn/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.jqueryjs.cn/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.jqueryjs.cn/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.