jQuery 属性操作 attr()、removeAttr()、prop()

173 阅读1分钟
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .dzm {
      border: 1px solid red;
    }
  </style>
  <script src="jquery-3.4.1.js"></script>
  <script>
    $(() => {
      // 获取元素,绑定属性
      var jqInput = $('input').eq(0);
      var jqCheckbox = $('input:checkbox');
      var jqBtn = $('button');

      jqBtn.click(function () {
        // 绑定普通属性,绑定到jquery的衣服上,标签上没有
        // jqInput.aaa = 111;
        // console.log(jqInput.aaa);

        // 绑定普通属性,绑定到标签上,标签上能看到
        jqInput.attr('title', 111);
        console.log(jqInput.attr('title'));

        // 绑定class, class带的css会生效
        jqInput.attr('class', 'dzm');
        console.log(jqInput.attr('class'));

        // 移除绑定
        // jqInput.removeAttr('class');

        // from 中的特殊属性,用 prop();
        // checked, selected, display 用 prop();
        jqCheckbox.prop('checked', true);
      })
    })
  </script>
</head>
<body>
  <button>绑定</button>
  <input type="text">
  <input type="checkbox">
</body>
</html>
  • demo 效果: