我想更改 Liregion2
类的所有 div
的所有 background-color
。
我只想更改 div
背景颜色,而不是 li
。
不过,我的代码只更改了一个 div
元素!我怎样才能让它影响所有的人?
这是我的 HTML5 代码:
<div class = "Liregion2" id = "LineBock1" style ="padding-bottom:3%;padding-left:10%;background-color:#ff9900">
<li>
<a href="#" id = "FirstLine" style="color:#fff;text-decoration: none" >1號線</a>
</li>
</div>
<div class = "Liregion2" id = "LineBock2" style ="padding-bottom:3%;padding-left:10%;">
<li>
<a href="#" id = "SecondLine" style="color:#009999;text-decoration: none" >2號線</a>
</li>
</div>
<div class = "Liregion2" id = "LineBock3" style ="padding-bottom:3%;padding-left:10%;">
<li>
<a href="#" id = "ThirdLine" style="color:#ff3366;text-decoration: none" >3號線</a>
</li>
</div>
<div class = "Liregion2" id = "LineBock4" style = "padding-left:10%;">
<li>
<a href="#" id = "ForthLine" style="color:#0066ff;text-decoration: none" >4號線</a>
</li>
</div>
这是 JQuery:
$('#FirstLine').click(function(){
$('.Liregion2').each(function( index , element ){
$(element).css("background-color" , "transparent");
});
event.stopPropagation();
});
最佳答案
css
方法在后台遍历集合,无需使用 each
循环。此外,您的标记无效,li
元素应该是 ul
/ol
元素的子元素。 div
元素应替换为上述元素之一(虽然它不会是语义标记。)
看来您只想操作父元素的 css
属性。如果是这种情况,您可以使用 .closest()
或 .parent()
方法:
// Do not miss the `event` object if you want to use it
$('.Liregion2 a').click(function(event) {
$(this).closest('.Liregion2').css("background-color" , "transparent");
event.stopPropagation();
});
作为避免使用内联样式的建议,它会使标记无法维护。您可以声明 CSS 类,并使用 jQuery removeClass
和 addClass
方法添加/删除它们。
关于javascript - 使用 JQuery 更改同一类中所有元素的 css 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25096728/