javascript - 更改元素 ID 后无法触发操作

标签 javascript jquery

我有一个显示/隐藏密码按钮,当我单击“显示密码”时,它会起作用,但当我尝试再次隐藏它时,它不会起作用。

fiddle :http://jsfiddle.net/vcvgj09z/

<input type="password" id="pass1" value="Now try to hide me">
<a href="#" id="show-password"><i class="fa fa-eye"></i> Show</a>

    $("#show-password").on("click",function() {
        $(this).html('<i class="fa fa-eye-slash"></i> Hide');
        $(this).prop("id","hide-password");
        $("#pass1").attr("type","text");
    });
    $("#hide-password").on("click",function() {
        $(this).html('<i class="fa fa-eye"></i> Show');
        $(this).prop("id","show-password");
        $("#pass1").attr("type","password");
    });

最佳答案

根据我的评论,您的代码不起作用的原因是因为元素 #hide-password 在运行时不存在于 DOM 中,因此 不会绑定(bind)任何点击事件到它

虽然您可以使用.on()来监听事件冒泡,但我强烈建议不要更改元素的ID。相反,您可以将切换开/关状态存储为 jQuery data 对象。这种方法的优点是:

  • 不依赖于更改标记和事件冒泡
  • 通过评估和修改 jQuery data 对象来存储密码的切换状态
  • 允许其他元素操纵/影响切换状态

请参阅此处的 fiddle :http://jsfiddle.net/teddyrised/vcvgj09z/10/

$('#toggle-password').click(function() {
    // Check state
    if(!$(this).data('state') || $(this).data('state') == 0) {
        // If the data object "state" is undefined or have a value of 0, convert password to text
        // Update HTML and data object
        $(this)
        .html('<i class="fa fa-eye-slash"></i> Hide')
        .data('state', 1);

        // Change password to text
        $("#pass1").attr('type', 'text');   
    } else {
        // If the data object "state" has a value of 1, convert text to password
        // Update HTML and data object
        $(this)
        .html('<i class="fa fa-eye"></i> Show')
        .data('state', 0);

        // Change text to password
        $("#pass1").attr("type","password");
    }
});

关于javascript - 更改元素 ID 后无法触发操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27321107/

相关文章:

JavaScript 运行时错误 : Unable to get property 'innerHTML' of undefined or null reference in asp. 网络

javascript - Angular 广播在第二次调用时未更新

javascript - 如何在 React 中将数组作为 props 传递而不转换为字符串

jquery - 缩略图助手 fancybox v2.0.6

javascript - 使用模块模式访问 jQuery 回调中的私有(private)变量

javascript - jquery animate jerky - 是否有更好的缩放图像库?

javascript - jison:如何在jison文件中添加 "require"?

jquery - Twitter Bootstrap Form Wizard/Jquery.validate - 如果表单无效,则阻止用户移至下一个选项卡

javascript - 三.js通过名称访问场景

javascript - Nuxt JS SSR 标题未定义