当用户单击“显示”链接时,显示密码,再次单击时将其隐藏 [英] When a user clicks Show link, display the password, hide it when clicked again
问题描述
我试图让这个简单的脚本工作。基本上,当用户单击显示链接时,它将在密码文本框中显示密码,并在再次单击时隐藏密码。我已经搜索了解决方案,但找不到任何我需要的东西。以下是代码:
I am trying to get this simple script to work. Basically, when a user clicks on the Show link, it will display the password in the password text box and hide it when it is clicked again. I have searched for solutions but couldn't find anything for what I need. Here is the code:
function toggle_password(target){
var tag = getElementById(target);
var tag2 = getElementById("showhide");
if (tag2.innerHTML == 'Show'){
tag.setAttribute('type', 'text');
tag2.innerHTML = 'Hide';
}
else{
tag.setAttribute('type', 'password');
tag2.innerHTML = 'Show';
}
}
HTML
HTML
<label for="pwd0">Password:</label>
<input type="password" value="####" name="password" id="pwd0" />
<a href="#" onclick="toggle_password('pwd0');" id="showhide">Show</a>
当我点击链接时,没有任何反应。我已经测试了这个,但没有使用if语句,但仍然没有做任何事情。
When I click the link, nothing happens. I have tested this without using the if statement too and still did nothing.
推荐答案
你没有使用文件
开启 getElementById
function toggle_password(target){
var d = document;
var tag = d.getElementById(target);
var tag2 = d.getElementById("showhide");
if (tag2.innerHTML == 'Show'){
tag.setAttribute('type', 'text');
tag2.innerHTML = 'Hide';
} else {
tag.setAttribute('type', 'password');
tag2.innerHTML = 'Show';
}
}
您的 id
名称是非法的并且难以使用: pwd'。$ x。'
你不能拥有其中一些字符。
your id
names are illegal and difficult to work with: pwd'.$x.'
you can't have some of those chars.
HTML 4.01规范规定ID令牌必须以字母([A-Za-z])开头,后面可以跟任意数量的字母,数字([ 0-9]),连字符( - ),下划线(_),冒号(:)和句点(。)。
The HTML 4.01 spec states that ID tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (-), underscores (_), colons (:), and periods (.).
此外,这种方法不适用于所有浏览器,在IE<例如,在元素附加到文档之前,您只能更改 .type
also, this method will not work in all browsers, in IE < 9 for instance you can only change .type
before the element is attached to the document
尝试交换它们:
function swapInput(tag, type) {
var el = document.createElement('input');
el.id = tag.id;
el.type = type;
el.name = tag.name;
el.value = tag.value;
tag.parentNode.insertBefore(el, tag);
tag.parentNode.removeChild(tag);
}
function toggle_password(target){
var d = document;
var tag = d.getElementById(target);
var tag2 = d.getElementById("showhide");
if (tag2.innerHTML == 'Show'){
swapInput(tag, 'text');
tag2.innerHTML = 'Hide';
} else {
swapInput(tag, 'password');
tag2.innerHTML = 'Show';
}
}
希望这有助于确认
这篇关于当用户单击“显示”链接时,显示密码,再次单击时将其隐藏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!