通过选择选项在>或<之间更改



我想根据我在select选项中所做的选择来比较两个输入的数字。你能告诉我怎么做吗?

let in1 = document.getElementById("num1").value
let in2 = document.getElementById("num2").value
let con = document.getElementById("condition").value
function run() {
if (in1 + con + in2) {
var a = "yes"
} else {
var a = "no"
}
console.log(a)
}
<input type="number" id="num1">
<select id="condition" name="condition" for="value">
<option value=">"> ></option>
<option value="<">
<</option>
<option value="==">= </option>
</select>
<input type="number" id="num2">
<br>
<button onclick="run()">compare</button>

你只是在连接字符串,而不是将它们作为表达式求值。

可以在包含测试适当条件的函数的对象中使用条件值是一个键。

function run() {
let in1 = parseInt(document.getElementById("num1").value);
let in2 = parseInt(document.getElementById("num2").value);
let con = document.getElementById("condition").value
const funcs = {
'<': (x, y) => x < y,
'>': (x, y) => x > y,
'==': (x, y) => x == y
};
if (funcs[con](in1, in2)) {
var a = "yes"
} else {
var a = "no"
}
console.log(a)
}
<input type="number" id="num1">
<select id="condition" name="condition" for="value">
<option value=">"> ></option>
<option value="<">
<</option>
<option value="==">= </option>
</select>
<input type="number" id="num2">
<br>
<button onclick="run()">compare</button>

使用额外的if...else语句来清楚地定义操作符是一个好主意。

let int1 = document.getElementById("num1").value
let int2 = document.getElementById("num2").value
let con = document.getElementById("condition").value

function run(int1, int2, con) {
Number(int1);
Number(int2);
if (con === "<") {
if (int1 < int2) {
let a = "yes";
return a;
} else {
let a = "no";
return a;
}
} else if (con === ">") {
if (int1 > int2) {
let a = "yes";
return a;
} else {
let a = "no";
return a;
}
} else if (con === "==") {
if (int1 === int2) {
let a = "yes";
return a;
} else {
let a = "no";
return a;
}
}
}

相关内容

最新更新