我在另一个函数中使用 javascript 创建了一个 div,并在我将要展示的函数中设置了样式(这一切正常)我试图用无序列表填充 div,这就是我所拥有的远:
function LeftSideMenu() {
// getting the javascript named div
var x = document.getElementById("sideMenu");
// Styling the div
x.style.width = "300px";
x.style.height = "750px";
x.style.position = "absolute";
x.style.padding = "0px 0px 0px 0px";
x.style.border = "thick solid #901709";
x.style.borderWidth = "10px";
x.style.background = "#c01e0c";
var sideList = ['About', 'Players', 'Achievements']
var unorderedList = document.createElement('ul');
for (var i = 0; i < sideList.Length; i++) {
// Create a new 'LI' element for each part of the sideList array
var theList = document.createElement('li');
// Set the contents of the list seen in "sideList"
theList.appendChild(document.createTextNode(sideList[i]));
// Appened the list to the unorderedList
unorderedList.appendChild(theList);
}
// Return the occupied list
return unorderedList;
}
所以问题是,如何用“sideList”内容填充列表并将该列表放入我的“sideMenu”(也称为 var = x)div。如果可能的话,我也想避免使用 JQuery。
最佳答案
你几乎所有的事情都做对了,除了:
您需要附加
unorderedList
在 DOM 的某处,以便它显示在页面上。如果您希望它位于sideMenu
中,然后在最后:x.appendChild(unorderedList);
您已经使用了
sideList.Length
而不是sideList.length
(小写l
在length
上)。 JavaScript 中的大小写很重要。
例子:
function LeftSideMenu() {
// getting the javascript named div
var x = document.getElementById("sideMenu");
// Styling the div
x.style.width = "300px";
x.style.height = "750px";
x.style.position = "absolute";
x.style.padding = "0px 0px 0px 0px";
x.style.border = "thick solid #901709";
x.style.borderWidth = "10px";
x.style.background = "#c01e0c";
var sideList = ['About', 'Players', 'Achievements']
var unorderedList = document.createElement('ul');
for (var i = 0; i < sideList.length; i++) {
// Create a new 'LI' element for each part of the sideList array
var theList = document.createElement('li');
// Set the contents of the list seen in "sideList"
theList.appendChild(document.createTextNode(sideList[i]));
// Appened the list to the unorderedList
unorderedList.appendChild(theList);
}
// Append the list to the menu div ***
x.appendChild(unorderedList); // ***
// Return the occupied list
return unorderedList;
}
LeftSideMenu();
<div id="sideMenu"></div>
关于javascript - 通过javascript创建一个无序列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40950793/