使用Array中的值创建元素

时间:2015-03-27 00:02:56

标签: javascript jquery html css arrays

嘿,我的阵列需要一些帮助。我可以看到,document.getElementById它捕获了我的值,但我想将值作为div中的背景样式。我知道它看起来很混乱<li><div>内部,但我真的迷失了,我无法让它发挥作用。

我需要为数组中的每个项目创建一个元素,并将它们作为背景颜色赋予它们。

如果我提出的问题没有意义,我很抱歉,因为它已经很晚了; - )

var noteColors = [
  { name: "red", value: "#FF396D" }, 
  { name: "green", value: "#C6DD2A" }, 
  { name: "blue", value: "#55C7F0" }, 
  { name: "purple", value: "#F64FC2" }, 
  { name: "yellow", value: "#F6DC2C" }];
<div id="note_colors_wrapper">
  <script type="text/javascript">
    var index;
    var text = "<ul id='colorss'>";

    for (index = 0; index < noteColors.length; index++) {
      text += "<li class='ol'>" + noteColors[index].value + "</li>";
    }
    text += "</ul>";
    document.getElementById("note_colors_wrapper").innerHTML = text;
    $(".ol").append("<div id='lo' style=background-color:" + 
      noteColors[index].value + ";></div>");
  </script>
</div>

最终结果应该是这样的 enter image description here

2 个答案:

答案 0 :(得分:0)

我开始稍微重新思考一下这个结构,你可能不希望你的脚本标签位于你想要替换其内容的元素中。

为了加快可维护性,使用HTMLElement API创建元素更有意义。这涉及使用document.createElementelement.appendChild等方法,而不是将元素构建为字符串并使用.innerHTML

最后,在您的代码中添加一些函数数组方法将大大简化您的解决方案。

Array.map可用于使用您选择的函数转换数组中的每个项目。

Array.forEach可用于循环遍历数组,而不必担心索引变量。

var items = noteColors.map(function(color) {
  var li = document.createElement('li');
  li.style.backgroundColor = color.value;
  return li;
});

var list = document.createElement('ul');
list.setAttribute('id', 'colors');
items.forEach(list.appendChild);

var wrapper = document.getElementById('note_colors_wrapper');
wrapper.appendChild(list);

答案 1 :(得分:0)

我觉得你很困。就像我国还早,也许我可以帮助你。

发生了什么事情,你搞砸了你的阵列。它不在脚本标签中。

我建议您按顺序使用代码,如下所示。

<html>
<head>
...... your head code
</head>
<body>
... body code

<div id="note_colors_wrapper"></div>

... more body code 

<script>
var noteColors = [
    { name: "red", value: "#FF396D" }, 
    { name: "green", value: "#C6DD2A" }, 
    { name: "blue", value: "#55C7F0" }, 
    { name: "purple", value: "#F64FC2" }, 
    { name: "yellow", value: "#F6DC2C" }];

var index;
var text = "<ul id='colorss'>";

for (index = 0; index < noteColors.length; index++) {
    //Note that in a very simple way, I assign the color in the style parameter of the <li>
    text += "<li class='ol' style='background-color:" + noteColors[index].value + "'>""</li>";
}
text += "</ul>";
document.getElementById("note_colors_wrapper").innerHTML = text;
</script>
</body>
</html>

https://jsfiddle.net/tLcxtmow/1/

中测试代码

希望这有帮助。