【问题标题】:How to loop through an array and set of dom elements and add the current item of the array to the current dom element?如何循环遍历一个数组和一组 dom 元素并将数组的当前项添加到当前 dom 元素?
【发布时间】:2023-03-08 06:23:01
【问题描述】:

我有一个包含 4 个字符串的 Jquery 数组:

var myArray = [ 1, 2, 3, 4 ];

在我的标记中,我有 4 个空 div,其他随机标记间歇性地分散在它们之间。

<div></div>
<p>Paragraph here</p>
<p>Paragraph here</p>
<div></div>
<h1>heading here</h1>
<p>Paragraph here</p>
<div></div>
<h1>heading here</h1>
<p>Paragraph here</p>
<div></div>

我想遍历数组并遍历 div 并将数组中当前项的文本添加到当前 div。我的标记中的最终结果应该是这样的:

<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>

您可能知道不是 javascript 专家,因此我们将不胜感激任何帮助。谢谢!

【问题讨论】:

标签: javascript jquery html arrays loops


【解决方案1】:

试试这个:

var myArray = [ 1, 2, 3, 4 ];
$('div').each(function(index){
    this.innerHTML = myArray[index];
});

演示here

【讨论】:

  • OP想要填写&lt;div&gt;s
  • +1,很好的答案。不过,您应该为.each() 提供指向jQuery API 的链接。
  • @Sergio Perfect,谢谢,我很感激。我会标记为已回答。
【解决方案2】:

如果您以后不关心数组为空,您可以使用:

var myArray = [ 1, 2, 3, 4 ];

$('div').each( function () {
    this.innerHTML = myArray.shift();
});

【讨论】:

    猜你喜欢
    • 2011-04-18
    • 2020-12-22
    • 2023-01-13
    • 2016-05-17
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    • 2018-07-29
    • 1970-01-01
    相关资源
    最近更新 更多