我有通過數組迭代的問題。我在一個html頁面上有x個具有相同x個表單的按鈕。與每個表單關聯的是表單上隨機數的複選框。按鈕selectControl選擇/取消選擇每個表單的所有複選框。按鈕和表單的名稱是通過使用一個元素並增加其編號來創建的。通過這種方式,我希望能夠通過這些元素循環保存其獨特的ID。
我收到一個錯誤「SyntaxError:missing; before statement」,但沒有發現與語法有關的任何內容,所以我想這必須是關於數組迭代的。JavaScript中的迭代問題
下面是我的代碼:
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>
你哪一行得到錯誤? – Musa
問題在這裏''selectControl「+ [r]'? – Harry
我通過esvalidate運行它,它是24行是越野車,我已經在下面給出瞭解決方案。 –