jQuery 添加属性

Sheeraz Gul 2022年6月15日
jQuery 添加属性

jQuery attr() 方法用于向 HTML 元素添加属性。本教程演示了如何在 jQuery 中使用 attr() 方法。

jQuery 添加属性

我们可以使用 jQuery 中的 attr() 方法为 HTML 元素添加属性。此方法的语法如下所示:

$(selector).attr("property", "Value")

其中,

  1. selector 可以是 id、class 或元素的名称。
  2. property 是属性的名称。
  3. value 是属性的值。

让我们试试一个例子:

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <title>jQuery Add Attribute</title>
      <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
      <script>
         $(document).ready(function(){
             $("#attr").click(function(){
                 $('input[type="checkbox"]').attr("checked", "checked");
             });
         });
      </script>
   </head>
   <body>
      <button type="button" id="attr">Click to Select the Checkbox</button>
      <input type="checkbox">
   </body>
</html>

上面的代码将检查未选中的复选框。该代码使用带有 attr() 方法的元素名称选择器,其中检查了属性,并检查了值。

查看输出:

添加属性

Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

相关文章 - jQuery Attribute