使用jQuery为多个同class的div内首个元素设置CSS失效问题排查
问题原因及解决方法
问题出在你的jQuery选择器作用域错误:
- 在
.each()循环里,直接写$("ul li:first a")是全局范围查找匹配元素,每次循环都会选中页面里第一个出现的ul li:first a(也就是第一个.axxs-tabs里的链接),所以第二个.axxs-tabs内的目标元素根本没被选中。
修复代码
把选择器限定在当前循环的.axxs-tabs元素内部,用$(this)作为上下文:
$(document).ready(function(){ $(".axxs-tabs").each(function(){ // 用$(this)限定查找范围在当前.axxs-tabs内部 $("ul li:first a", this).css("background-color", "yellow"); // 也可以写成更直观的形式: // $(this).find("ul li:first a").css("background-color", "yellow"); }); });
另外,其实不需要.each()也能实现需求,直接用后代选择器一次性选中所有符合条件的元素,写法更简洁:
$(document).ready(function(){ $(".axxs-tabs ul li:first a").css("background-color", "yellow"); });
这种写法下,jQuery会自动遍历所有.axxs-tabs下的ul li:first a元素,统一为它们添加样式。
内容的提问来源于stack exchange,提问作者DeanH
相关产品推荐
相关产品推荐

