2012-11-16 61 views
0

大家好我想創建這樣一個場景,每一次我點擊「轉換」 I「#one」之間切換,「#two」和「#three」單格觸發切換

我不能弄清楚如何啓動的jQuery

<div class="switch">swicth</div> 
<div id="one">1</div> 
<div id="two">2</div> 
<div id="three">3</div> 

<style> 
#one, #two, #three{ 
    display:none; 
} 
</style> 
+0

咦?它們之間的「切換」是什麼意思?現在他們都是看不見的。 – thatidiotguy

+0

當你切換時應該發生什麼? – kinakuta

+0

那麼,有什麼必須嘗試?你需要通過綁定div上的'click'事件開始'.switch' –

回答

1

我會用類選擇器將允許你有任何數量的這樣的div的。

DEMO:http://jsfiddle.net/m7gSn/2/

<div class="switch">swicth</div> 
<div id="one" class="myc">1</div> 
<div id="two" class="myc">2</div> 
<div id="three" class="myc">3</div> 
<style> .myc { display:none; } </style> 

JS:

var $myc= $('.myc'); 
var cp = 0; 

$('.switch').click (function() {  
    $myc.hide().eq(cp++).show();  
    if (cp == $myc.length) cp = 0;   
}); 
+0

yep..makes感......實際上這將是理想的 – soum

+0

我適應了這個解決方案 – soum

4

試試這個:

$(".switch").toggle(
    function() { hideAll(); $("#one").show(); }, 
    function() { hideAll(); $("#two").show(); }, 
    function() { hideAll(); $("#three").show(); } 
); 

function hideAll() { 
    $("#one, #two, #three").hide(); 
} 

Example fiddle

+0

Rory ......完美......那就是我一直在尋找的東西。太棒了 – soum

0

我想出了這個。添加類的toggle到要旋轉的div後之間:

$(".switch").click(function() { 
    var toggle = $(".toggle:visible"); 
    if (toggle[0]) { 
     $(toggle[0]).hide(); 
     var next = $(toggle[0]).next(".toggle"); 
     if (next[0]) { 
     $(next[0]).show(); 
     } 
     else { 
     $(".toggle").first().show(); 
     } 
    } 
    else { 
     $(".toggle").first().show(); 
    }   
}); 

Demo

0

一個小魔術:

$('.switch').click(function() { 
    var c = $.data(this, 'index', ($(this).data('index') || 1) % 3 + 1); 
    $('div').hide().eq(c-2).show(); 
}); 

演示:https://tinker.io/0d614

+0

這很酷 – soum