将 jquery 转换为 vanilla js?

时间:2021-07-07 13:50:09

标签: javascript jquery

JS 新手。我正在使用 http://youmightnotneedjquery.com/https://tobiasahlin.com/blog/move-from-jquery-to-vanilla-javascript/ 将我的 jquery 代码更改为 vanilla js。当用户单击眼睛图标时,他们可以显示他们的密码并再次单击以隐藏密码。我想出了这个:

jQuery:

    $('.toggle-password').click(function () {
      $(this).toggleClass('eye-slash eye-open');
      const input = $($(this).attr('toggle'));
      if (input.attr('type') === 'password') {
        input.attr('type', 'text');
      } else {
        input.attr('type', 'password');
      }
    });

JavaScript:

    document.querySelector(".toggle-password").addEventListener("click", () => {
      this.classList.toggle("eye-slash eye-open");
      const input = this.getAttribute("toggle");
      if (input.getAttribute("type") === "password") {
        input.setAttribute("type", "text");
      } else {
        input.setAttribute("type", "password");
      }
    });

HTML

<input type="password" id="signup-password" />
<span toggle="#signup-password" class="eye-slash toggle-password"></span>

错误是:

Uncaught TypeError: Cannot read property 'toggle' of undefined
    at HTMLSpanElement.<anonymous> (sign_up:588)

我对 const input = $($(this).attr('toggle')); 的转换可能不正确,但我不确定原因。

1 个答案:

答案 0 :(得分:2)

您使用箭头函数作为事件侦听器的回调,这意味着它从其父作用域继承 this,因此 this 关键字并不是您认为的那样。这是 jQuery 为您做的非常好的事情,但它在 vanilla JS 中可能有点混乱。

通过从 event.target(回调的第一个参数)访问 event,您可以访问在 document.querySelector(".toggle-password") 中引用的元素。

document.querySelector(".toggle-password").addEventListener("click", (event) => {
          const $this = event.target;
          $this.classList.toggle("eye-slash eye-open");
          
          const input = $this.getAttribute("toggle");
          if (input.getAttribute("type") === "password") {
            input.setAttribute("type", "text");
          } else {
            input.setAttribute("type", "password");
          }
    });