我正在尝试验证我的保管箱,以确保用户已选择测验。但是当我在 Dropbox 中选择不同的测验时,结果等于"1",它会提醒我,但它无法正常运行,它会在结果等于"0"时运行代码。
<select id="quiz" onchange="check()">
<option value="0">Select Quiz</option>
<?php foreach ($datas as $data) : ?>
<option value="1"><?php echo $data['Title']; ?></option>
<?php endforeach; ?>
</select>
<script>
var x = false;
function check() {
var e = document.getElementById("quiz");
var result = e.options[e.selectedIndex].value;
alert(result);
if(result = "0") {
alert("Select a quiz");
}else if (result = "1") {
alert("UTM");
x = true;
}
}
function Validate() {
if(x == true) {
alert("UTM");
} else {
alert ("Please select a quiz");
}
}
</script>
</b>
</label>
<button type="enter" onclick="Validate()">Confirm Selection</button>
如果 X = true,您的验证函数甚至不会读取状态,即使它已经被 onchange 修改,因此输出将始终为 false。
我建议将更改和验证功能合并为一个,因为在这种情况下,两个相同的功能无关紧要
1 = 1也不起作用,使用==或===
<select id="quiz">
<option value="0">Select Quiz</option>
<option value="1">Quiz1</option>
<option value="1">Another quiz</option>
</select>
<button type="enter" onclick="Validate()">Confirm Selection</button>
<script>
function Validate() {
var e = document.getElementById("quiz");
var result = parseInt(e.options[e.selectedIndex].value);
alert(result);
if(result == 0) {
alert("Select a quiz");
}else if (result == 1) {
alert("UTM");
x = true;
}
}
</script>
我认为您的if
语句的代码中有拼写错误。
if(result = "0") {
在这里,您正在做一个作业,因此此条件将为 alwais true。
你应该做什么:
if(result == "0") {
或if(parseInt(result) === 0) {
下面的行也是如此:else if (result = "1") {
你听说过尤达条件吗? 它有助于避免那些小错误。
https://en.wikipedia.org/wiki/Yoda_conditions