循环遍历数组,将每个值分配给Javascript / Jquery中的元素属性

时间:2017-06-10 20:28:51

标签: javascript jquery arrays

我有一个数组:'imageIds':

imageIds = ["778", "779", "780", "781", "782"];

我想在页面上找到类.preview-image的所有元素,其中我知道该数字将与数组的长度相匹配。

然后,我想为第一个匹配元素分配一个数据属性'data-img-id',其值为imageIds [0],第二个匹配元素为imageIds [1]等。

所以最终的结果就是转换它:

<div class="preview-image">...</div>
<div class="preview-image">...</div>
<div class="preview-image">...</div> etc

到此:

<div class="preview-image" data-img-id="778">...</div>
<div class="preview-image" data-img-id="779">...</div>
<div class="preview-image" data-img-id="780">...</div> etc

不太确定如何形成实现此目的的循环。

3 个答案:

答案 0 :(得分:3)

选择元素然后使用each循环遍历它们,它将当前元素的索引传递给它的回调:

$(".preview-image").each(function(index) {
    $(this).attr("data-img-id", imageIds[index]);
});

示例:

var imageIds = [100, 200, 300];

$(".preview-image").each(function(index) {
  $(this).attr("data-img-id", imageIds[index]);
});
.preview-image::after {
  content: "data-img-id is: " attr(data-img-id);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="preview-image">...</div>
<div class="preview-image">...</div>
<div class="preview-image">...</div>

答案 1 :(得分:3)

您可以迭代id数组并将该属性赋值给具有相同索引的类数组的相同元素。

&#13;
&#13;
<div class="preview-image"></div>
<div class="preview-image"></div>
<div class="preview-image"></div>
<div class="preview-image"></div>
<div class="preview-image"></div>
&#13;
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
loop = asyncio.get_event_loop()
resolver = aiodns.DNSResolver(loop=loop)
sem = asyncio.Semaphore(MAX_COUNT)
&#13;
&#13;
&#13;

答案 2 :(得分:2)

可能是这样的:我不确定你怎么“知道”这个数字会与数组长度相匹配。无论哪种方式,都可以很容易地从array.length更改它并添加数据属性..

var imageIds = ["778", "779", "780", "781", "782"];

var elements = document.querySelectorAll('.preview-image');
for(var i=0; i < elements.length; i++) {

    elements[i].dataset.imgId = imageIds[i];

    console.log(elements[i].dataset);
}
<div class="preview-image">...</div>
<div class="preview-image">...</div>
<div class="preview-image">...</div>