我将下面的“名称”字段的函数以及按钮按下时的函数称为onblur。对于onblur,innerHTML的值写得很好,并在文本框旁边显示。但是,当我单击按钮时,即使调用了该函数并且所有循环都工作正常,也无法对innerHTML位进行写入。我已经全神贯注,但是不明白我在做什么错?
function Valid(name) {
alert("check1");
var name = document.getElementById("name").value;
if (name.length < 2) {
alert("length < 2");
document.getElementById("error").innerHTML = "Message 1";
return false;
} else {
var reg = /^[a-z]+$/i;
if (reg.test(name.charAt(0))) {
alert("FIrst character is alphabet");
document.getElementById("error").style.display = "none";
} else {
alert("First character not alphabet");
document.getElementById("error").innerHTML = "Message2";
return false;
}
}
return name;
}
<article>
<form>
<table style="width:100%">
<tr>
<td><label>Name</label></td>
<td colspan="1"><input type="text" id="name" /></td>
<td colspan="2"><output id="error"></output></td>
</tr>
</table>
</form>
</article>
答案 0 :(得分:0)
这是有效的代码,希望对您有所帮助。它对我有用。
function Valid(){
var regName = /^[a-zA-Z]+$/i;
var name = document.getElementById('name').value;
if (name.toString().length < 2) {
alert("length < 2");
document.getElementById("error").innerHTML = "Message1";
return true;
}else{
if(regName.test(name.charAt(0))){
alert("FIrst character is alphabet");
document.getElementById("error").style.display = "none";
return true;
}else{
document.getElementById("error").innerHTML = "Message2";
alert("First character not alphabet");
return false;
}
}
}
<article>
<form>
<table style="width:100%">
<tr>
<td><label>Name</label></td>
<td colspan="1"><input type="text" id="name" onkeyup="Valid()"/></td>
<td colspan="2"><output id="error"></output></td>
</tr>
</table></form></article>