我试图给每个列表元素一个不同的颜色.但是,我只有2种颜色,但有10种永久链接.
我的问题:
只要有永久链接,我希望颜色再次循环.
var colors = ['#ff9f9d', '#EB1B53']; $('a.permalink').each(function(i) { $(this).css('color', colors[i]); console.log($(this)); });
如果它到达终点,确保它再次启动颜色数组的最佳方法是什么?
尝试使用模数运算符来获取提醒
var colors = ['#ff9f9d', '#EB1B53']; $('a.permalink').each(function (i) { $(this).css('color', colors[i % colors.length]); console.log($(this)); });
它可以缩短为
$('a.permalink').css('color', function (i) { return colors[i % colors.length]; });
演示:小提琴