您可以使用以下代码来使用 jQuery 将索引为偶数的 div 背景色改为绿色:

$(document).ready(function() { 
  // 获取所有的 div 元素
  var divs = $('div');
  
  // 使用 each() 方法迭代每个 div 元素
  divs.each(function(index) { 
    // 检查索引是否为偶数
    if (index % 2 === 0) { 
      // 将背景色改为绿色
      $(this).css('background-color', 'green');
    } 
  });
});

在上述代码中,我们首先通过 $('div') 选择器获取所有的 div 元素,并将它们存储在 divs 变量中。然后,我们使用 each() 方法遍历每个 div 元素。在每次迭代中,我们检查当前索引是否为偶数,通过使用 % 运算符和数字 2 来判断。如果索引为偶数,我们使用 $(this) 来引用当前的 div 元素,并使用 css() 方法将背景色设置为绿色。


原文地址: https://www.cveoy.top/t/topic/pK7K 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录