javascript - 通过javascript创建一个无序列表

标签 javascript html css

我在另一个函数中使用 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。

最佳答案

你几乎所有的事情都做对了,除了:

  1. 您需要附加 unorderedList在 DOM 的某处,以便它显示在页面上。如果您希望它位于 sideMenu 中,然后在最后:

    x.appendChild(unorderedList);
    
  2. 您已经使用了 sideList.Length而不是 sideList.length (小写 llength 上)。 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/

相关文章:

javascript - 内联 jquery 字符串 - 为某些单词添加粗体

javascript - 我在哪里失去了随机性?

javascript - 使网页内容半透明,点击或悬停时更透明

css - 维护 CSS 层次结构

html - 将 CSS 过渡设置为使用速度而不是持续时间?

CSS使背景图像覆盖其他div

html - btn 没有在中间垂直对齐

Javascript 模块,在可能未加载时传递 jQuery

javascript - 如何检测表格每一行的<td>之一的文本是否发生变化?

javascript - 如何判断客户端是否是触摸设备