我一直在用单选按钮进行测试。一切似乎都很好,直到我通过 JS lint 运行它。我修复了除一个以外的所有错误:
出乎意料的“为”
for (i = 0; i < radios.length; i += 1) {
这是我的Javascript:
/*global body,window,document,alert*/
(function () {
"use strict";
var UIlogic;
UIlogic = {
myLoad: function () {
var elems, elemText, btn1, winter, summer, fall, spring, header, btns;
winter = "<div><input type='radio' name='cb' id='cbA' value='0'/><label for='cbA'>Winter</label></div>";
summer = "<div><input type='radio' name='cb' id='cbB' value='1'/><label for='cbB'>Summer</label></div>";
fall = "<div><input type='radio' name='cb' id='cbC' value='2'/><label for='cbC'>Fall</label></div>";
spring = "<div><input type='radio' name='cb' id='cbD' value='3'/><label for='cbD'>Spring</label></div>";
header = "Header";
btns = "<br /><button class='btns' id='btn1'>Go!</button>";
elemText = "Menu/nav";
elems = "<center><div>" + header + "</div></center>";//title
elems += "<div>" + elemText + "</div></center>";//menu
elems += "<div id='container'><br />";//container opens
elems += "<div id='div1'>" + winter + "</div>";
elems += "<div id='div2'>" + summer + "</div>";
elems += "<div id='div2'>" + fall + "</div>";
elems += "<div id='div2'>" + spring + "</div>";
elems += "<div id='div3'>" + btns + "</div>";
elems += "</div>";//container closes
elems += "<h6><div id='footer'>Ehawk 2015</div></h6>";
body.innerHTML = elems;
btn1 = document.getElementById("btn1");
btn1.addEventListener('click', UIlogic.intoFunction, false);
},
intoFunction: function () {
var radios, found, i = 0;
radios = document.getElementsByName("cb");
found = 1;
for (i = 0; i < radios.length; i += 1) {//issue occurs here
if (radios[i].checked) {
alert(radios[i].value);
found = 0;
break;
}
}
if (found === 1) {
alert("Please Select Radio");
}
}
};
window.onload = function () {
UIlogic.myLoad();
};
}());
我运行我的循环错了吗?为什么 JSlint 会在这里看到问题,即使认为代码有效?我真的可以对循环使用一些见解,因为我对它们的问题最多。我被告知不要使用它们,但我没有看到运行循环来检测单选按钮和检查收音机的问题。这是我应该关心的事情吗?