Jquery modify elements in each loop

こ雲淡風輕ζ 提交于 2021-02-07 08:39:46

问题


Using jquery, I want to loop all elements having the class "item" and apply different background colors according to the index of the element.

mapcolor is an array of colors (length = number of elements having "item" class)

$.each($(".item"), function(i,e){
$("#"+e).css("background-color",mapcolor[i]);
});

$("#"+e) selector doesn't work as expected, neither $("#"+e.id) ... Something's wrong with my selector. Any idea?


回答1:


use .each() method instead and you have to be in the context with $(this):

$(".item").each(function(i){
  $(this).css("background-color",mapcolor[i]);
});

Yet a better way is:

$(".item").css("background-color",function(){
    return mapcolor[$(this).index()];
});

make use of .css() method and pass a callback function to return the value.

A test is below:

var mapcolor = ['green', 'red', 'yellow'];

$(".item").css("background", function() {
  return mapcolor[$(this).index()];
});
div{height:10px;}
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



回答2:


yes problem is in your selector ... problem is on this like

$("#"+e).css("background-color",mapcolor[i]);

why you using # with e because # represent id .. but here e is representing current selected tag in loop

so simply use $(e).css("background-color",mapcolor[i]); in your way..

or short and better way use this

$(".item").each(function(i){
    $(this).css("background-color",mapcolor[i]);
});



回答3:


Try something like this:

$( ".item" ).each(function(i) {
  $(this).css("background-color",mapcolor[i]);
});


来源:https://stackoverflow.com/questions/32092973/jquery-modify-elements-in-each-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!