使用jQuery each()在DOM元素中加载数组元素的问题

时间:2021-05-10 13:43:23

Can you please take a look at this code and let me know how I can use the .each() to load each elements of array to the buttons?

您能否看一下这段代码,让我知道如何使用.each()将数组的每个元素加载到按钮上?

var arr=["Left","Middle", "Right" ];
 $("button").each(function(){
        $(this).html(arr);
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btn-group" role="group" aria-label="...">
  <button type="button" class="btn btn-default">x</button>
  <button type="button" class="btn btn-default">x</button>
  <button type="button" class="btn btn-default">x</button>
</div>

2 个解决方案

#1


1  

You certainly can. You use the index of each button in the DOM and use it to iterate through the array

你当然可以。您使用DOM中每个按钮的索引并使用它来遍历数组

var arr=["Left","Middle", "Right" ];
 $("button").each(function(i){
        $(this).html(arr[i]);
    });

http://jsfiddle.net/d14z32fq/

#2


1  

If the array order is the desired, use the index parameter provided by the .each() method:

如果数组顺序是所需的,请使用.each()方法提供的index参数:

var arr = ["Left","Middle", "Right"];
$("button").each(function(i){
    $(this).html(arr[i]);
});

#1


1  

You certainly can. You use the index of each button in the DOM and use it to iterate through the array

你当然可以。您使用DOM中每个按钮的索引并使用它来遍历数组

var arr=["Left","Middle", "Right" ];
 $("button").each(function(i){
        $(this).html(arr[i]);
    });

http://jsfiddle.net/d14z32fq/

#2


1  

If the array order is the desired, use the index parameter provided by the .each() method:

如果数组顺序是所需的,请使用.each()方法提供的index参数:

var arr = ["Left","Middle", "Right"];
$("button").each(function(i){
    $(this).html(arr[i]);
});