我正在使用此脚本隐藏页面上输入元素的默认值:
<script>
var active_color = '#000'; // Colour of user provided text
var inactive_color = '#ccc'; // Colour of default text
window.onload = formDefaultValues;
function formDefaultValues() {
var fields = getElementsByClassName(document, "input", "default-value");
if (!fields) {
return;
}
var default_values = new Array();
for (var i = 0; i < fields.length; i++) {
fields[i].style.color = inactive_color;
if (!default_values[fields[i].id]) {
default_values[fields[i].id] = fields[i].value;
}
fields[i].onfocus = function() {
if (this.value == default_values[this.id]) {
this.value = '';
this.style.color = active_color;
}
this.onblur = function() {
if (this.value == '') {
this.style.color = inactive_color;
this.value = default_values[this.id];
}
}
}
}
}
function getElementsByClassName(oElm, strTagName, strClassName){
var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
var arrReturnElements = new Array();
strClassName = strClassName.replace(/\-/g, "\\-");
var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
var oElement;
for (var i = 0; i < arrElements.length; i++) {
oElement = arrElements[i];
if (oRegExp.test(oElement.className)) {
arrReturnElements.push(oElement);
}
}
return (arrReturnElements);
}
</script>
我使用此代码循环输入具有类&#34;默认值&#34;并对他们开火。它真的在某些元素上工作但不在其他元素上吗?可能出现什么问题?
提前致谢
答案 0 :(得分:0)
这对我有用..
<html>
<script>
function ViewAllElements() {
var fe = document.forms['myForm'].elements;
alert(fe.length);
for(var i = 0; i < fe.length; i++)
{
alert(fe[i].value);
}
var ebc = getElementsByClassName(document, "input", "fieldA");
alert(ebc.length);
for(var j = 0; j < ebc.length; j++)
{
alert(ebc[j].value);
}
}
function getElementsByClassName(oElm, strTagName, strClassName){
var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
var arrReturnElements = new Array();
strClassName = strClassName.replace(/\-/g, "\\-");
var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
var oElement;
for (var i = 0; i < arrElements.length; i++) {
oElement = arrElements[i];
if (oRegExp.test(oElement.className)) {
arrReturnElements.push(oElement);
}
}
return (arrReturnElements);
}
</script>
<body>
<form id="myForm" name="myForm">
<input class="fieldA" id="field1" name="field1" value="field1value">
<input class="fieldA" id="field2" name="field2" value="field2value">
<input class="fieldA" id="field3" name="field3" value="field3value">
<input class="fieldB" id="field4" name="field4" value="field4value">
<input class="fieldB" id="field5" name="field5" value="field5value">
<input class="fieldB" id="field6" name="field6" value="field6value">
<input type="button" onClick="ViewAllElements();" value="View">
</form>
</body>
</html>