2016-11-24 105 views
0

我想通過jQuery索引來更改元素的css。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罰款指標,但似乎PF畫廊指數沒有加載。到目前爲止它不工作。

+1

工作對我很好......難道份額可執行代碼段.. .. – Rayon

+0

工作正常https://jsfiddle.net/nu4ngh31/ – Satpal

回答

1

看起來好像在你的代碼中一切正常。

如果你想重置在每個背景顏色點擊,你可以將其設置爲''

$(".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>