jQuery修改每个循环中的元素 [英] Jquery modify elements in each loop

查看:54
本文介绍了jQuery修改每个循环中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用jquery循环所有具有"item"类的元素,并根据元素的索引应用不同的背景颜色.

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是颜色的数组(长度=具有"item"类的元素的数量)

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)选择器无法正常工作, $(#" + e.id)都没有...我的选择器出了点问题.有什么主意吗?

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

推荐答案

改用 .each()方法,您必须使用 $(this):

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

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

一个更好的方法是:

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

使用 .css()方法并传递一个回调函数以返回值.

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

下面是一个测试:

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>

这篇关于jQuery修改每个循环中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆