我通过数组迭代遇到了这个问题。我在一个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>
答案 0 :(得分:0)
var selectControl[r] = document.getElementById("selectControl"+[r]);
你的意思是:
selectControl[r] = document.getElementById("selectControl" + r);
你也应该声明:
var selectControl = [ ];
靠近代码顶部(在任何函数声明之前)。
最后,您应该在代码的末尾加上一个结束注释标记。