我做了一個簡單的 if else 條件,它應該顯示輸入的兩個輸入中哪個是更大的數量,但它顯示的值與預期的相反。這是怎么回事?提前致謝!
HTML:
<input type= "text" id="texto">
<input type= "text" id="texto2">
<button type="submit" id="enviar">Enviar</button>
JS:
const texto = document.getElementById('texto');
const texto2 = document.getElementById('texto2');
const send = document.getElementById('send');
send.addEventListener('click', mayorque)
function mayorque() {
if (texto > texto2){
alert('Input 1 is greater than input 2')
} else {
alert('Input 2 is greater than input 1')
}
}
uj5u.com熱心網友回復:
幾個問題。
當您在加載時設定變數texto時,它會在加載時獲取輸入的值。您將需要獲取函式中的值。
使用類似parseFloat的東西會將值轉換為數值。浮點數將允許小數點。
let texto = document.getElementById('texto');
let texto2 = document.getElementById('texto2');
const send = document.getElementById('send');
send.addEventListener('click', mayorque)
function mayorque() {
texto = parseFloat(texto.value);
texto2 = parseFloat(texto2.value);
if (texto > texto2) {
alert('Input 1 is greater than input 2')
} else {
alert('Input 2 is greater than input 1')
}
}
<input type="text" id="texto">
<input type="text" id="texto2">
<button type="submit" id="send">Enviar</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/496034.html
標籤:javascript if 语句
下一篇:一次打開一個手風琴部分。(苗條)
