这个想法是有两个选择框的测试。因此,必须在以下每个选择框中选择一个选项。每个选择框中只有一个选项是正确的,其他选项是错误的。
通过单击按钮,必须看到alert
他们的答案是对还是错。
循环实际上获取页面的所有选择框,但代码不想工作。
如何选中一个按钮是否选择了两个不同选择框中的两个特定选项?
function check() {
var rt = $(document).find('select');
var count = rt.length;
for (i = 0; i < count; i++) {
$(rt[i]).change(function() {
var val = $(this).children("option:selected").val();
var right = $(this).children("option:selected").data('accept');
if (val === right) {
alert('right')
} else {
alert('wrong')
}
});
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="country" id="first">
<option>-</option>
<option>United States</option>
<option data-accept="India" value="right">India</option>
<option>United Kingdom</option>
<option>Russia</option>
</select>
<select class="country" id="second">
<option>-</option>
<option data-accept="United States" value="right">United States</option>
<option>India</option>
<option>United Kingdom</option>
<option>Russia</option>
</select>
<button type="button" onclick="check()">check</button>
您不需要在页面的每个选择上循环。这是一个有效的代码:
function check() {
if (isSelectRight("#first") && isSelectRight("#second")) {
alert("right");
} else {
alert("wrong");
}
}
function isSelectRight(selectId) {
const selected = $(selectId + " option:selected");
return selected.attr("value") === "right";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="country" id="first">
<option>-</option>
<option>United States</option>
<option data-accept="India" value="right">India</option>
<option>United Kingdom</option>
<option>Russia</option>
</select>
<select class="country" id="second">
<option>-</option>
<option data-accept="United States" value="right">United States</option>
<option>India</option>
<option>United Kingdom</option>
<option>Russia</option>
</select>
<button type="button" onclick="check()">check</button>
基本上,你有一个函数selectisRight
,它根据选项的selectId
属性检查传递的value
的选定值是否正确。
你可以在你想要的每个select
上使用它。