<div class="newfile" >
<ul>
<li><input value="test1" type="radio" name="abc" onclick="getResults()" /></li>
<li><input value="test2" type="radio" name ="abc" onclick="getResults()" /></li>
<li><input value="test1" type="radio" name ="xyz" onclick="getResults()"/></li>
<li><input value="test2" type="radio" name="xyz" onclick="getResults()" /></li>
</ul>
</div>
这是我现在的html,如果任何两个具有相同值的单选按钮,如=“test2”或“test1”,则会给我提醒
我试图在循环中获得价值
<script>
function getResults() {
var radios = document.getElementsByTagName("input");
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
alert(radios[i].value);
break;
}
}
}
</script>
但没有得到如何比较两个选中按钮的值并获得警报。
我希望如果任何两个具有相同值的单选按钮给我提醒,则不会发生任何事情。
答案 0 :(得分:0)
这个怎么样:
<script type="text/javascript">
function getResults() {
var radios = document.getElementsByTagName("input");
var values = new Array();
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
var found = false; //Represents if we have a duplicate
for(var j = 0; j < values.length; j++) { //Loop through previous items
if(values[j] == radios[i].value) { //Duplicate?
found = true; // Flag it
break; //Exit 'j' loop
}
}
values[values.length] = radios[i].value; //Add value to previous items
if(!found) continue; //If there was no duplicate, continue to next item
alert(radios[i].value); //There was a duplicate, alert and return
break;
}
}
}
</script>
答案 1 :(得分:0)
愿这有帮助吗?
function getResults() {
var radios = document.getElementsByTagName("input");
var dupDetector = {};
var value;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
// value = radios[i].value; // add a prefix to avoid built-in property names
value = 'I_' + radios[i].value;
if (dupDetector[value]) {
alert(radios[i].value);
return;
}
dupDetector[value] = true;
}
}
}
感谢@meiamsome警告我,如果value
是内置对象属性,谓词将始终为true,尽管没有重复项。要避免它,请为其添加一个虚拟前缀。