我在我的网站上input type="text"
,我试图编写代码,可以检查字段是否为空。
if (number>0)document.getElementById("score").innerHTML="+";
else if (number<0)document.getElementById("score").innerHTML="-";
else if (number==0)document.getElementById("score").innerHTML="0";
else document.getElementById("score").innerHTML="this is not a number";
当该字段为空时,它仍然显示输入“0”。
____修改
var number = document.getElementById("field").value;
<input type="text" id="field">
答案 0 :(得分:3)
这是一个有效的解决方案,当输入字段为空时,score
div中不显示任何内容。 (如果需要,您可以将其更改为显示消息。)
var score = document.getElementById('score');
document.getElementById('field').addEventListener('keyup', checkNum);
function checkNum() {
var number = parseInt(document.getElementById('field').value);
if (number>0) score.innerHTML="+";
else if (number<0) score.innerHTML="-";
else if (number==0) score.innerHTML="0";
else if (document.getElementById('field').value=="") score.innerHTML="";
else score.innerHTML="this is not a number";
}
&#13;
#score {
display: inline-block;
border: 2px solid red;
border-radius: 4px;
font-weight: 700;
padding: 4px;
}
&#13;
<input type="text" id="field">
<br><br>
<div id="score"></div>
&#13;