在问这个问题之前,我探索了如何将元素动态添加到列表中的现有答案,并将其中的几个纳入了我的解决方案,以满足我的需求。但是,似乎该列表从未被填充。我在想这个问题可能与访问列表来追加元素有关,但我不完全确定。如何动态填充HTML页面上的列表
我的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> Start Studying </button>
</div>
</div>
<div class="col-sm-4" id="student">
<h3> Student Decks </h3>
<ul id="student_list"> </ul>
</div>
我别的调用JavaScript函数,其中在HTML文件中,我已经证实,该函数被调用,参数是我所期望的,并且循环运行相应的次数。
这是我的javascript功能:
function populateLists(json) {
for (var i = 0; i < json.length; i++){
//Create a new list element
var list_item = document.createElement('li');
list_item.setAttribute('name', 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 = document.getElementById('row').getElementById((json[i].faculty=='1')?'faculty':'student' + '_list');
list.append(list_item);
}
}
您可以创建一个plunker例子来证明这一点?它看起来像你的HTML缺少一些关闭的div标签。我不能看到,与ID“行”的div是关闭。另外,不是特别清楚,如果你真的想添加新创建的'li'元素div或ul。 –