我的 HTML 檔案中的這段代碼用作執行計算的函式。它會提示用戶輸入房間數和總平方英尺,然后將平方英尺乘以 5 以獲得估計值。我試圖弄清楚如果用戶輸入負數,如何添加 if 陳述句作為錯誤訊息。下面是從代碼中復制的函式。我會直接在函式中添加它,在它之前還是之后?我主要想說的是,
if (var a && b <= 0) {
print "Invalid entry. Please reload the page and enter a positive number." }
我將如何在 JavaScript 中執行此操作?另外,是否有比使用 < p> </p> 更好的方式詢問用戶?
<div class="container-fluid">
<p>Please enter the number of rooms affected, and the total square foot. </p>
<input type="text" name="numRooms" id="numRooms"> <br>
<input type="text" name="roomSize" id="roomSize"><br>
<button type="button" onclick="submit1()">submit</button><br>
<p id="result"></p>
</div>
<script>
function submit1(){
var a = document.getElementById("numRooms").value;
var b = document.getElementById("roomSize").value;
var c = parseInt(b) * 5;
document.getElementById("result").innerHTML="Your estimate is : $" c;
}
</script>
uj5u.com熱心網友回復:
如果發生錯誤,您可以提前檢查值并提前退出。
function submit1() {
var a = document.getElementById("numRooms").value; // get a number with
var b = document.getElementById("roomSize").value;
var c = parseInt(b) * 5;
if (isNaN(a) || a <= 0 || isNaN(b) || b <= 0) { // check if number or smaller/eq than zero
document.getElementById("result").innerHTML = '<span style="color: #b00;">Please insert only positive numbers.</span>';
return;
}
document.getElementById("result").innerHTML = 'Your estimate is : $ ' c;
}
<div class="container-fluid">
<p>Please enter the number of rooms affected, and the total square foot. </p>
<input type="text" name="numRooms" id="numRooms"> Rooms<br>
<input type="text" name="roomSize" id="roomSize"> Size [sq ft]<br>
<button type="button" onclick="submit1()">submit</button><br>
<p id="result"></p>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/354742.html
標籤:javascript 功能 if 语句
上一篇:為什么我的計數器不能正確計數?雖然我的if陳述句沒有填充,但它增加了 1
下一篇:如何在dart中撰寫If陳述句?
