简体   繁体   English

jQuery的每个填充元素逐渐从数组

[英]jquery each fill elements gradually from array

Hello I would like to fill gradually span elements with values of array. 您好,我想用array的值逐步填充元素。 Can you help me please? 你能帮我吗?

<span class="gt"></span>
<span class="gt"></span>
<span class="gt"></span>

var array=["apple","banana","cucumber"];

$("span.gt").each(function(){
    $(this).text(array[?]);
});

Output should look like this: 输出应如下所示:

<span class="gt">apple</span>
<span class="gt">banana</span>
<span class="gt">cucumber</span>

You get the index value in the function for each loop. 您可以在函数中获得each循环的index值。 And since the number of span elements is equal to the number of items in the array variable you can use that index value to set the array values in the span elements: 并且由于span元素的数量等于array变量中的项目数,因此您可以使用该index值来设置span元素中的数组值:

 var array=["apple","banana","cucumber"]; $("span.gt").each(function(index){ $(this).text(array[index]); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span class="gt"></span> <span class="gt"></span> <span class="gt"></span> 

  1. You can use for loop. 您可以使用for循环。
  2. Use the increment number as index of the span and index of array 使用增量数作为范围的索引和数组的索引

 var array = ["apple", "banana", "cucumber"]; for (var i = 0; i < array.length; i++) { $('span').eq(i).text(array[i]); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span class="gt"></span> <span class="gt"></span> <span class="gt"></span> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM