【问题标题】:How to give value form array to div如何将值形式数组赋予div
【发布时间】:2022-01-27 05:44:19
【问题描述】:

我有坐标数组和相同数量的 div。现在我需要从数组中获取第一个值来给出第一个 div 等等。

这里是数组的例子

var xList = [265, 152, 364]
var yList = [125, 452, 215]

每个数组都有三个值,三个 div 也是如此

<div class"box">Box</div>
<div class"box">Box</div>
<div class"box">Box</div>

如何将第一个值赋予第一个 div 第二个赋予第二个 div,依此类推。

我正在考虑像这样使用 css。

$(".box").css({ top: yList + "px", left: xList + "px" });

我尝试在这里使用 for 循环:

for (var i = 0; i < xList.length && i < yList.length; i++) {
        box.style.top = yList[i] + "px";
        box.style.left = xList[i] + "px";
    }

但它没有工作。 这只是一个例子,它不是我的真实代码,除了这个 for 循环。这个例子类似于我的真实代码我有相同数量的 div 作为数组中的值,我需要给第一个 div 第一个值第二个 div 第二个值等等. 我的所有代码都在这个链接上https://jsfiddle.net/SutonJ/5gyqexhj/35/

【问题讨论】:

    标签: javascript html jquery css arrays


    【解决方案1】:

    在提供的示例中,您没有区分“box”类的三个不同对象。我希望你会发现 jQuery 的 each() 方法很有用:

    $(".box").each(function(index) {
       $(this).css({top: yList[index] + "px", left: xList[index] + "px"}) );
    });
    

    ... 此处记录:https://api.jquery.com/each/

    【讨论】:

      猜你喜欢
      • 2012-01-02
      • 2014-05-01
      • 1970-01-01
      • 2020-06-20
      • 2023-04-03
      • 2022-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多