我想通过 jQuery 索引更改元素的 css。
$(".switcher span").click(function() {
var galleryIndex = $(this).index();
$('.wrapper .gallery').eq(galleryIndex).css("background", "red");
});
<div class="switcher">
<span>Switch 0</span>
<span>Switch 1</span>
</div>
<div class="wrapper">
<div class="gallery">GALLERY 0</div>
<div class="gallery">GALLERY 1</div>
</div>
jQuery 获取 .switcher span
的索引正常,但似乎画廊的索引未加载。到目前为止它不起作用。
最佳答案
看起来您的代码中的一切都运行良好。
如果您想在每次点击时重置背景色,您可以将其设置为''
:
$(".switcher span").click(function(){
var galleryIndex = $(this).index();
$('.wrapper .gallery').css('background', '').eq(galleryIndex).css("background", "red");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="switcher">
<span>Switch 0</span>
<span>Switch 1</span>
</div>
<div class="wrapper">
<div class="gallery">GALLERY 0</div>
<div class="gallery">GALLERY 1</div>
</div>
关于javascript - jQuery 通过索引更改 css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40786067/