我试图让用户点击复选框的位置,它将输入框中的密码显示为文本。如果他/她取消选中,它会将属性设置为密码。任何指针?
代码:
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='jquery-3.1.1.min.js'></script>
<script type='text/javascript' src='jquery-ui/jquery-ui.js'></script>
<script type='text/javascript'>
$(document).ready(function(){
$('#check').click(function(){
if($('test-input').attr('type', 'text'));
});
});
</script>
</head>
<body>
<input type='password' id='test-input' /> Show password <input type='checkbox' id='check' />
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
做这个 :
$('#check').click(function(){
if('password' == $('#test-input').attr('type')){
$('#test-input').prop('type', 'text');
}else{
$('#test-input').prop('type', 'password');
}
});
Run Code Online (Sandbox Code Playgroud)
您在选择器中的 test-input 之前缺少 # 并且每次单击它时都需要检查复选框的状态
<script type='text/javascript'>
$(document).ready(function(){
$('#check').click(function(){
alert($(this).is(':checked'));
$(this).is(':checked') ? $('#test-input').attr('type', 'text') : $('#test-input').attr('type', 'password');
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
我做了这个小片段:
$('.toggle-password').click(function(){
$(this).children().toggleClass('mdi-eye-outline mdi-eye-off-outline');
let input = $(this).prev();
input.attr('type', input.attr('type') === 'password' ? 'text' : 'password');
});Run Code Online (Sandbox Code Playgroud)
<link href="https://cdnjs.cloudflare.com/ajax/libs/MaterialDesign-Webfont/4.7.95/css/materialdesignicons.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<div class="form-group col-6">
<label>Password</label>
<div class="input-group">
<input type="password" class="form-control" name="password" autocomplete="new-password" minlength="6">
<div class="input-group-append toggle-password">
<span class="input-group-text mdi mdi-eye-outline"></span>
</div>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
它与 jQuery 一起使用,对于样式我使用了 Bootstrap,图标来自 Material Icons。
这项工作正确:
$('#check').click(function(){
if(document.getElementById('check').checked) {
$('#test-input').get(0).type = 'text';
} else {
$('#test-input').get(0).type = 'password';
}
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='password' id='test-input' /> Show password <input type='checkbox' id='check' />Run Code Online (Sandbox Code Playgroud)
JSFIDDLE: https: //jsfiddle.net/0xuue3v6/