【问题标题】:How to translate Javascript to jQuery [closed]如何将 Javascript 转换为 jQuery [关闭]
【发布时间】:2020-05-07 12:36:22
【问题描述】:

如何将这段代码翻译成 jQuery?我是 javascript 世界的新手。

var show = document.querySelectorAll('.js-show');

for (let i = 0; i <= show.length; i++) {
    var hide = document.querySelectorAll('.js-hide');

    for (let i = 0; i <= hide.length; i++) {
        show[i].addEventListener('click', function() {
            if (hide[i].type === 'password') {
                hide[i].type = 'text';
                show[i].innerHTML = 'visibility';
            } else {
                hide[i].type = 'password';
                show[i].innerHTML = 'visibility_off';
            }
        });
    }
}

感谢您的帮助。

【问题讨论】:

  • 首先不要在每次迭代中都这样做var hide = document.querySelectorAll('.js-hide');
  • 你也可以在纯JS中委托
  • 您想要将 Javascript 转换为 jQuery 的任何具体原因?
  • 你知道你可以在for循环中使用除i之外的其他字母作为变量吗?变量可以是多个字符,甚至包括数字,只要数字不是第一个字符。

标签: javascript jquery web frameworks coding-style


【解决方案1】:

您的原版 JS 不是最理想的。同时查看您的 HTML 也会有所帮助

我相信你想要这个

$('.js-show').on("click",function() {
  const $pw = $(this).closest(".someContainer").find(".pw");
  $pw.attr("type", $pw.attr("type")==="password" ? "text" : "password");
  $(this).val($pw.attr("type")==="password" ? "visibility" : "visibility_off");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="someContainer">
  <input type="button" class="js-show" value="visibility" /> <input class="pw" type="password" />
</div>  
<div class="someContainer">
  <input type="button" class="js-show" value="visibility"/> <input class="pw" type="password" />
</div>

【讨论】:

    猜你喜欢
    • 2016-01-14
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-31
    • 2012-05-09
    • 2011-04-01
    相关资源
    最近更新 更多