我正在尝试遍历包含复选框的HTML列表,以获取与每个复选框关联的id
。但是,我编写的Javascript上的forEach()
函数会出现以下错误:Uncaught TypeError: faculty_deck_list.forEach is not a function
。我试图按如下方式遍历ID:
var decks = []; //Store the decks
var faculty_deck_list = document.getElementById('faculty_list').getElementsByTagName('input');
var student_deck_list = document.getElementById('student_list').getElementsByTagName('input');
faculty_deck_list.each(function () {
decks.push($(this).id);
});
student_deck_list.each(function () {
decks.push($(this).id);
});
我正在生成包含以下元素的列表:
function populateLists(json) {
for (var i = 0; i < json.length; i++){
//Create a new list element
var list_item = document.createElement('li');
list_item.appendChild(document.createTextNode(Object.values(json)[i].name));
//Create the checkbox to add to the list element
var select_checkbox = document.createElement('input');
select_checkbox.type = 'checkbox';
select_checkbox.id = json[i].deck_ID;
//Add the checkbox to the list element
list_item.appendChild(select_checkbox);
var list_name = (json[i].faculty=='1')?'faculty':'student' + '_list';
list = document.getElementById(list_name);
list.append(list_item);
}
}
HTML是:
<div class="row" id="row">
<div class="col-sm-4" id="faculty">
<h3> Faculty decks </h3>
<ul id="faculty_list"> </ul>
</div>
<div class="col-sm-4">
<h3> Instructions </h3>
<p> Select your decks, select front (questions) or back (answers) of the the card and start studying. </p>
<div>
<input class="front" type="radio" name="card" id="front" value="Front"> Front  </input>
<input class="back" type="radio" name="card" id="back" value="Back"> Back</input>
<br />
<br />
<button id="study"> Start Studying </button>
</div>
</div>
<div class="col-sm-4" id="student">
<h3> Student Decks </h3>
<ul id="student_list"> </ul>
</div>
</div>
编辑: 按钮单击的Javascript函数调用初始函数以获取选择:
$("#study").click(function() {
alert("CLICKED");
//Get the selected decks
var selection = getDeckSelections();
if(selection.length > 0) {
//Get the selected side of the card
var selected_side = $('input[name=side_selection]:checked', '#side_selection_form').val();
//Store the selected side in session storage
sessionStorage.setItem("selected_side", selected_side);
//Ajax call to get cards from database
$.ajax({
url: "get_cards.php",
type: "GET",
data: {selection:JSON.stringify(selection)},
cache: false,
async: false,
success: function(data) {
json = JSON.parse(data);
//Store the cards in session storage
sessionStorage.setItem("cards", JSON.stringify(json));
}
});
}
});
答案 0 :(得分:0)
问题是document.getElementsByTagName
返回节点列表,节点列表不支持each()
方法。
由于您使用的是JQuery,因此请更改代码,以便将节点列表转换为支持each()
的JQuery对象:
$(faculty_deck_list).each(function () { ...
答案 1 :(得分:0)
如果您不想使用jQuery,还可以将节点列表转换为数组:
var faculty_deck_list = Array.from(document.getElementById('faculty_list').getElementsByTagName('input'))