2010-08-12 179 views
1

我試圖找到一種簡單的方法來將點擊事件附加到一個元素,這對於第一次和第二次點擊事件來說是相當容易的。但是,我試圖完成的是三次點擊切換。如何爲第三次點擊分配jQuery點擊事件?

1st click = addClas('one'); 2nd click = removeClass('one')。addClass('two'); 3rd click = removeClass('two')。addClass('three'); 下次點擊會==第一次點擊並再次通過循環..

我使用一個簡單的div和通過CSS應用樣式,更改元素背景位置 - 所有非常典型和容易..並且是蛋糕做一個切換()或點擊()事件..但我無法弄清楚我的生活如何處理第三次點擊! :d

這裏是我的標記,例如用途:

任何幫助是極大的讚賞!

UPDATE: 我有一些作品..但,恕我直言,它的醜陋和雜亂..還有得是一個更清潔,這樣做的更簡潔的方式: $(「 tri_switch」)。點擊(函數(){VAR this_id = $(本).attr( 「ID」);

if($(this).hasClass("one")){     
    $("input#user_"+this_id).attr('checked','checked'); 
    $("input.tri_switch_radio").not("#user_"+this_id).removeAttr('checked'); 
    $(this).removeClass('one').addClass('two'); 
    $("span.tri_switch_checked").text('User'); 
} 
else if ($(this).hasClass("two")){ 
    $("input#admin_"+this_id).attr('checked','checked'); 
    $("input.tri_switch_radio").not("#admin_"+this_id).removeAttr('checked'); 
    $(this).removeClass('two').addClass('three'); 
    $("span.tri_switch_checked").text('Admin'); 

} 
else if ($(this).hasClass("three")){ 
    $("input#readonly_"+this_id).attr('checked','checked'); 
    $("input.tri_switch_radio").not("#readonly_"+this_id).removeAttr('checked'); 
    $(this).removeClass('three').addClass('one'); 
    $("span.tri_switch_checked").text('Readonly'); 

} 

//警報(this_id); });

+0

我甚至想過增加一個計數值,並在第三次點擊LOL時重新設置它。只要它的'乾淨的編碼',我對任何使這項工作開放的東西都是開放的:D – revive 2010-08-12 09:31:52

回答

5

Yup @Codler,toggle()可以比默認的兩個參數多。只是扔在第三個參數:

$('#element').toggle(function(){ 
    $(this).addClass('one'); 
}, 
function(){ 
    $(this).removeClass('one').addClass('two'); 
}, 
function(){ 
    $(this).removeClass('two').addClass('three'); 
}); 
+0

B E A U T I F U L!我以爲我曾經見過一個案例,其中有人用第三個參數切換(),但是在搜索並沒有發現任何東西的情況下,我把它寫成了條形圖回憶LOL 謝謝,這會很好地工作。 – revive 2010-08-12 11:03:07

1
var counter = 0; 
$(".button").bind("click",function(){ 
    counter++; 
    switch(counter){ 
     case 1: 
      doSomething(); 
      break; 
     case 2: 
      doSomething2(); 
      break; 
     case3: 
      doSomething(3); 
      counter=0; 
      break; 
    } 
}) 

是你想要的?

+0

在最後一種情況下..你的意思是'case 3'或'case3',你鍵入? 另外,在這種情況下..你有doSomething(3); 應該是doSomething3(); ?? 只是想確保我清楚地理解你的例子..我不會錯過任何東西。謝謝 – revive 2010-08-12 10:59:44

+0

它是我的錯,很抱歉。 情況3和doSomething3()。在任何情況下,你都可以調用一些函數。只需要將計數器重置爲最後一種情況即可。 (在這個例子3中) – Anakin 2010-08-13 05:37:42