2016-03-11 14 views
0
 var svg = document.getElementById("svg");   
     var isToggled = svg.classList.contains("toggled");  
     if (!isToggled) { 
      $(".svg:first").addClass("svg toggled"); 
     } else { 
       i++ 
       $(".svg:first").next(i).addClass("svg toggled"); 
     } 

所以基本上,有與class和id名爲「SVG」 5個SVG標籤,我想在類名稱更改爲「SVG切換」逐一。在momoent中,它只改變第一個和第二個svg的類名,然後在那之後停止。JQuery的下一個()addClass()逐個

如何爲所有svg標籤逐個添加類名?

回答

0

使用.nextAll([selector])瞄準所有的兄弟姐妹後,第一個匹配元素:

$(".svg:first").nextAll().addClass("svg toggled"); 
+0

但這不會一個一個做,對不對? – WcPc

+0

是的,我也試過這個,不過謝謝。 – rayrayj92

+1

你可以發佈完整的代碼,希望看到你到目前爲止的整個循環 –

0

的以下更改else將類添加到剩餘的元素與半秒的每個

else { 
    $(".svg:not(:first)").each(function(i, element){ 
     setTimeout(function(){ 
      $(element).addClass("toggled"); 
     }, 500*i); // 500 is the delay in milliseconds 
    }); 
} 
之間的延遲

更新演示在https://jsfiddle.net/gaby/rh9t15r3/21/

+0

@ user2068889根據您的代碼更新了演示的答案。 –

0

你需要一個循環接一個地做一些事情之一:

// This creates an array of all the svg elements 
var svg = $("#svg"); 

//Loop the svg-array 
$.each(svg, function() { 
    // Check if the current element already has a "toggled" class 
    if(!$(this).hasClass("toggled") { 
     // Add it if not. 
     $(this).addClass("svg toggled"); 
    } 
    else { 
     i++; // whatever i is 
     // If the current svg already has the "toggled" tag you do not have to add it, right? 
    } 
}