问题描述
我试图让这个简单的脚本工作.基本上,当用户单击 Show 链接时,它会在密码文本框中显示密码,并在再次单击时将其隐藏.我一直在寻找解决方案,但找不到任何我需要的东西.代码如下:
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
<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 <9 例如,您只能在元素附加到文档之前更改 .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';
}
}
希望这有助于 -ck
这篇关于当用户点击显示链接时,显示密码,再次点击时隐藏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!