【问题标题】:Loop over nested array and render divs with values循环嵌套数组并使用值渲染 div
【发布时间】:2018-06-20 12:30:26
【问题描述】:

我有一个看起来有点像这样的数组:

arr = [
  ["10", "1", "1200", "630"],
  ["272", "45", "654", "654"],
  ["10", "139", "367", "372"],
  ["825", "134", "369", "371"]
];

每个数组内部的值是我要渲染的 div 的参数(x、y、宽度、高度)。所以例如第一个 div 应该有道具:

left: 10,
top: 1,
width: 1200,
height: 630

我当前的实现如下所示:

for (var i = 0; i < arr.length; i++) {
      $('<div/>', {
          class: 'class-' + i
        }).appendTo($('body'));
      for (var j = 0; j < arr[i].length; j++) {
            $('.class-' + i).css({
                position: 'absolute',
                left: arr[i][j],
                top: arr[i][j],
                width: arr[i][j],
                height: arr[i][j]
         });
     }
}

所以在这种情况下,我想为每个数组创建 4 个不同的 div,并在每个数组中给出正确的 CSS 样式。 不幸的是,它不起作用,因为我在索引方面遇到了一些问题。

你知道如何解决这个问题吗?

谢谢!

【问题讨论】:

  • “因为我面临一些索引问题。” > 什么问题?发生了什么,您预计会发生什么?
  • 分享 html 以及你想要什么结果以及你得到什么错误?

标签: javascript jquery html arrays loops


【解决方案1】:

问题出在这部分代码上:

for (var j = 0; j < arr[i].length; j++) {
        $('.class-' + i).css({
            position: 'absolute',
            left: arr[i][j],
            top: arr[i][j],
            width: arr[i][j],
            height: arr[i][j]
        });
}

您必须为给定的 div 设置 样式一次。在您的代码中,它为每个具有class-i 的div 设置css 样式4 次,其中i= 1 to arr.length。

arr = [
       ["10px", "1px", "12", "63"],
       ["272px", "45px", "65", "65"],
       ["101px", "139px", "36", "37"],
       ["825px", "134px", "36", "31"]
     ];
for (var i = 0; i < arr.length; i++) {
        $('<div/>', {
            class: 'class-' + i
        }).appendTo($('body'));
        $('.class-' + i).css({
                position: 'absolute',
                left: arr[i][0],
                top: arr[i][1],
                width: arr[i][2],
                height: arr[i][3]
        });
}
div{
  background-color:red;
  border:1px solid black;
}
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

  • 嗨,米海!感谢您的输入 - 您的解决方案和 ItsGregs 解决方案似乎都可以正常工作,但都无法识别左侧和顶部的值。你知道为什么吗?
  • @Akr,现在看看。看来您必须使用 px 为 top 和 left 属性设置值。
【解决方案2】:

您可以使用.map(),将对象传递给.css()。另请注意,left 和 top 值应将 "px" 连接到数值

arr = [
  ["10px", "1px", "1200", "630"],
  ["272px", "45px", "654", "654"],
  ["10px", "139px", "367", "372"],
  ["825px", "134px", "369", "371"]
];
$("body")
  .append(
    arr.map(([left, top, width, height], i) =>
      $("<div>", {
        "class": "class-" + i,
        text: i,
        css: {left, top, width, height}
      }))
  );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>

plnkrhttp://plnkr.co/edit/4DgX13CoQAy9QC8oUA1T?p=preview

【讨论】:

  • 谢谢,非常优雅的解决方案!也会考虑这个!感谢您的贡献!
  • @AKr 我会尽量避免循环或 forEach-ing 而不花大量时间调查 map、reduce/recursion 和 filter
  • @AKr 评论太长,但这里是all the array functions
  • @HMR 谢谢!我将更深入地研究这些功能。谢谢指出!
【解决方案3】:

你不想重复第二次。在您的第一个for 循环中,您会得到["10", "1", "1200", "630"]。如果你再次循环它,你会得到一个值。这就是你要找的东西——我对 jQuery 有点生疏,你可以优化它。

for (var i = 0; i < arr.length; i++) {
    var parent =  $('<div/>', {
        class: 'class-' + i
    }).appendTo($('body'));
    $('.class-' + i).css({
        position: 'absolute',
        left: arr[i][0],
        top: arr[i][1],
        width: arr[i][2],
        height: arr[i][3]
    });
}

【讨论】:

    【解决方案4】:

    这是给你的fiddle。希望对您有所帮助。

    var arr = [
           ["10", "1", "1200", "630"],
           ["272", "45", "654", "654"],
           ["10", "139", "367", "372"],
           ["825", "134", "369", "371"]
         ];
         
     arr.forEach(function(a) {
     	var div = $('<div/>').css({
        left: a[0],
        top: a[1],
        width:a[2],
        height: a[3]
      });
     	$('body').append(div);
     });
    &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

    【讨论】:

    • 我会给你一个 +1 的努力,但forEach 混合了将 div 添加到 dom 和创建 div dom 元素的副作用。 guest271314 的答案使用 map 返回一个 div 数组,然后您可以在 dom 中输入这些数组(副作用)。如果您想将 crating div 拆分并用它们做一些单独的函数,那么使用 map 会更好,因为它只创建 div。
    • @HMR 谢谢哥们 :) 这是一个很好的建议,可以在未来优化我的答案。
    【解决方案5】:

    for (var i = 0; i < arr.length; i++) {
      $('<div/>', {
        class: 'class-' + i
      }).appendTo($('body'));
      $('.class-' + i).css({
        position: 'absolute',
        left: arr[i][0],
        top: arr[i][1],
        width: arr[i][2],
        height: arr[i][3]
      });
    
    }

    你只需要一个循环。

    【讨论】:

      【解决方案6】:

      这里是一个使用reduce和递归函数的例子:

      var arr = [
        ["10px", "1px", "1200", "630"],
        ["272px", "45px", "654", "654"],
        ["10px", "139px", "367", "372"],
        ["825px", "134px", "369", "371"]
      ];
      var mapValuesToCss = ([left, top, width, height])=>
        Object.assign(
          {left,top}
          ,{
            width:width+"px",
            height:height+"px"
          }
        );
      var addIndexAsContent = (value,index)=>value.html(index)
      var createDivsReduce = css =>
        css.reduce(
          (divs,css)=>
            divs.concat(
              $(
                "<div>",
                css
              )
            )
          ,[]
        );
      var createDivsRecursive = divs => css => {
        if(css.length===0){
          return divs;
        }
        return createDivsRecursive
          (divs.concat($("<div>",css[0])))
          (css.slice(1));//recursively call itself
      }
      //using reduce
      $("body")
        .append(
          createDivsReduce(arr.map(mapValuesToCss))
          .map(addIndexAsContent)
        );
      //recursively
      $("body")
        .append(
          createDivsRecursive([])(arr.map(mapValuesToCss))
          .map(addIndexAsContent)
        );
      &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-15
        • 2022-01-14
        • 2020-12-16
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 2019-11-09
        • 2020-05-14
        相关资源
        最近更新 更多