jQuery实现密码可见性切换时Invalid left-hand side in assignment报错解决
问题成因
- 触发
Uncaught ReferenceError: Invalid left-hand side in assignment的直接原因,是内联onclick中的赋值逻辑违反JS语法规则。jQuery的.attr('type')单参数调用返回的是输入框当前type属性的字符串值(属于不可被写入的常量),JS语法明确禁止将函数返回的固定值放在赋值号=的左侧。如果要修改jQuery选中元素的属性,必须通过.attr(属性名, 新属性值)的传参形式完成,不能对attr()的返回值直接赋值。 - 除了核心报错,现有代码还存在多处会导致功能失效的问题,就算修好这行语法错误也无法实现密码切换效果:
- 事件绑定语法错误:脚本中写的
$(":input[type=password]").click, function (e) {用逗号分隔了.click()方法和回调函数,根本没有完成点击事件的绑定,回调函数完全不会触发 - 无效逻辑:
input.attr('type') == 'password' ? 'text' : 'password';这行三元运算虽然计算出了目标type值,但没有将结果赋值回输入框属性,属于没有实际作用的空转代码 - 选择器方向错误:
$(this).closest('input')的作用是从当前触发元素向上遍历,查找最近的祖先匹配元素。如果事件绑定在密码输入框上,输入框本身不可能是自己的祖先,这个选择器完全选不中目标元素;如果事件绑定在按钮上,按钮和输入框是兄弟节点,向上遍历也找不到输入框 - 语法残片:代码中混入了多余的反引号、不匹配的大括号,本身就会触发JS解析错误
- 事件绑定语法错误:脚本中写的
修复方案
最小改动版(仅修复当前报错)
把按钮上错误的onclick逻辑替换为正确的jQuery属性设置写法:
<button class="form-password__visibility" type="button" onclick="const pwdInput = $('#inputPassword'); const targetType = pwdInput.attr('type') === 'password' ? 'text' : 'password'; pwdInput.attr('type', targetType);"> <i class="vi vi-eye-off"></i> </button>
规范写法(推荐,实现图标同步切换)
去掉按钮上的内联点击逻辑,把所有交互逻辑收敛到脚本层,同时修正之前的选择器和事件绑定错误:
- 修正后的HTML结构
<!--Hide/Show password--> <button class="form-password__visibility" type="button"> <i class="vi vi-eye-off"></i> </button> <input type="password" id="inputPassword">
- 修正后的脚本逻辑
// 给密码切换按钮绑定点击事件,不要把事件绑在密码输入框本身 $('.form-password__visibility').click(function () { const pwdInput = $('#inputPassword'); const currentType = pwdInput.attr('type'); const targetType = currentType === 'password' ? 'text' : 'password'; // 设置输入框的type属性完成密码/明文切换 pwdInput.attr('type', targetType); // 同步切换按钮上的眼睛图标状态 const icon = $(this).children('i'); if (targetType === 'password') { icon.removeClass('vi-eye').addClass('vi-eye-off'); } else { icon.removeClass('vi-eye-off').addClass('vi-eye'); } });
内容的提问来源于stack exchange,提问作者sara
相关产品推荐
相关产品推荐

