function ageVerify() {
var age1 = Number(document.getElementById("age1").value);
var voteable;
if (isNaN(age1) || document.getElementById("demo1").innerHTML == "") {
voteable = "Please type a number";
} else {
voteable = (age1 < 18) ? "Too young":"Old enough";
}
document.getElementById("demo1").innerHTML = voteable;
}
&#13;
<p>Input your age and click the button:</p>
<input id="age1" placeholder="type your age" />
<button onclick = "ageVerify()">Verify the age</button>
<p id="demo1"></p>
&#13;
您好。当我玩条件(tenary)函数时,我发现了它的有趣方面以及它的极限。现在,如果用户没有输入数字或任何内容,他们会收到一条消息&#34;请输入一个数字。&#34;并且取决于他们的年龄超过18岁或18岁以下,他们会得到“太年轻”和“#34;足够老”&#34;。
一切都很好,直到我发现当我尝试在输入数字后用空输入再次验证年龄时,innerHTML(&#34;太年轻&#34;)不会消失或被&#34取代;请输入一个数字&#34;当我没有打字的时候。如果我事先没有输入数字,它就可以工作,但是一旦我输入数字,信息就不会消失。有没有办法循环这个功能?我希望我能解释清楚。
感谢您的阅读。
答案 0 :(得分:3)
发生的事情是您在第一个if语句中测试了错误的值。由于您使用Number(document.getElementById("age1").value)
将age1转换为数字,因此空输入永远不会是NaN
,而是将为0.并且因为已设置的值也不会通过。这就是为什么它不会改回你想要的文本。
另外,如果您设置元素的文字,最佳做法是使用.textContent
而不是.innerHTML
请尝试使用以下代码段。
function ageVerify() {
var age1 = Number(document.getElementById("age1").value);
var voteable;
if (isNaN(age1) || !document.getElementById("age1").value) {
voteable = "Please type a number";
} else {
voteable = (age1 < 18) ? "Too young" : "Old enough";
}
document.getElementById("demo1").textContent = voteable;
}
<p>Input your age and click the button:</p>
<input id="age1" placeholder="type your age" />
<button onclick="ageVerify()">Verify the age</button>
<p id="demo1"></p>
答案 1 :(得分:0)
请将您的Javascript功能更改为此功能。
Revenue = 20$
Cost = 0.914 * 17.5 = 16
Margin = 4
Margin % = 20