【发布时间】:2013-09-16 15:41:54
【问题描述】:
我在通过数组进行迭代时遇到了这个问题。我在一个 html 页面上有 x 个具有相同 x 个表单的按钮。与每个表单相关联的是表单上随机数量的复选框。按钮 selectControl 选择/取消选择每个表单的所有复选框。按钮和表单的名称是通过使用元素并增加其编号来创建的。通过这种方式,我希望能够遍历这些元素并保留它们的唯一 ID。
我收到一个错误“SyntaxError: missing ; before statement”但没有发现任何与语法有关的东西,所以我猜这必须是关于通过数组进行迭代。
下面是我的代码:
var run_times = 2; //declare how many buttons
//function to look for checkboxes in each form
//receive the array of selectControl buttons from window.onload = function()
function Check(frm){
//get all checkboxes in an array
var checkBoxes = frm.elements['chbx'];
//run this for every form as specified in run_times var
for (r = 0; r < run_times; r++) {
//and for each checkbox found
for (i = 0; i < checkBoxes.length; i++){
checkBoxes[i].checked = (selectControl[r].innerHTML == "Select All") ? 'checked' : '';
}
//set the inner html for each button
selectControl[r].innerHTML = (selectControl[r].innerHTML == "Select All") ? "Unselect All" : 'Select All';
};
};
window.onload = function()
{
//loop
for (r = 0; r < run_times; r++)
{
//get a variable for each button
var selectControl[r] = document.getElementById("selectControl"+[r]);
//pass each of these variables to function above when button clicked
selectControl[r].onClick= function(){ Check(document.myform[r])};
};
};
/*window.onload = function(){
var selectControl = document.getElementById("selectControl");
selectControl.onclick = function(){Check(document.myform)};
};
这是我的 html
<form name="myform1" method="" action="">
<ul class="list-group" style="list-style:none">
<li class="reco_item"><input name="chbx" class="reco_inp_box"type="checkbox"><p>one</p></li>
<li class="reco_item"><input name="chbx" class="reco_inp_box"type="checkbox"><p>one</p></li>
<li class="reco_item"><input name="chbx" class="reco_inp_box"type="checkbox"><p>one</p></li>
<li class="reco_item"><input name="chbx" class="reco_inp_box"type="checkbox"><p>one</p></li>
<li class="reco_item"><input name="chbx" class="reco_inp_box"type="checkbox"><p>one</p></li>
<li class="reco_item"><input name="chbx" class="reco_inp_box"type="checkbox"><p>one</p></li>
<li class="reco_item"><input name="chbx" class="reco_inp_box"type="checkbox"><p>one</p></li>
<li class="reco_item"><input name="chbx" class="reco_inp_box"type="checkbox"><p>one</p></li>
</ul>
</form>
<button id="selectControl1" name="sr_btn" class="btn btn-info reco_btn pull-right">Select all</button>
</div>
【问题讨论】:
-
你在哪一行得到了错误?
-
这里有问题
"selectControl"+[r]? -
我通过 esvalidate 运行了这个,第 24 行有问题,我在下面给出了解决方案。
-
肯定是的,但这不是这里的问题..
-
如果这是您的完整代码,您可能需要关闭
window.onload =块周围的注释(最后缺少*/)。
标签: javascript arrays loops checkbox