2012-07-26 33 views
2

這是一個動畫只應如果DIV rip_tab有類「rip_tab_ripped」,被點擊的DIV之後施加火。但是,即使在rip_tab_ripped類切換之前,動畫也會觸發。每個函數都獨立工作,沒有if子句。任何幫助將是appreciated--jQuery的,如果hasclass然後運作

var sauceSquirt = { 
    init: function() { 

     $("#rip_tab").click(function() { 
      $(this).toggleClass("rip_tab_ripped"); 
     }); 



     function fireA() { 
      $("#sauceRed").switchClass("sauce_hide", "sauceRedGo", 500) 
     } 

     function fireB() { 
      $("#sauceBlue").switchClass("sauce_hide", "sauceBlueGo", 500) 
     } 

     if ($('#rip_tab').hasClass("rip_tab_ripped")) { 


      $('#packet').click(function() { 

       var events = [fireA, fireB]; 

       //declare counter 
       if (!this.counter) { 
        this.counter = 0; 
       } 

       events[this.counter](); 
       this.counter = (this.counter + 1) % 3; 
      }); 



     } 

    } 

} 

$(document).ready(function() { 
    sauceSquirt.init(); 

});​ 

回答

7

看起來像您有這部分的麻煩:

if ($('#rip_tab').hasClass("rip_tab_ripped")) { 
    $('#packet').click(function() { 

     var events = [fireA, fireB]; 

     //declare counter 
     if(!this.counter) { this.counter = 0; } 

     events[this.counter](); 
     this.counter = (this.counter + 1) % 3; 
    }); 
} 

你能只是將其更改爲:

$('#packet').click(function() { 
    if ($('#rip_tab').hasClass("rip_tab_ripped")) { 

      var events = [fireA, fireB]; 

      //declare counter 
      if(!this.counter) { this.counter = 0; } 

      events[this.counter](); 
      this.counter = (this.counter + 1) % 3; 
    } 
    return false; 
}); 

你也可以在你想耽誤上課檢查,直到看一看jQuery Promise

0

分辨率是到如果($聲明移到點擊下面的語句行。

0

什麼是#packet? 在我看來,有這種說法應該這樣寫:

this.counter = this.counter % 2; 
0

請記住,當你初始化本方法都被調用時, #packet點:

$('#packet').click(function() { 
    if ($('#rip_tab').is('.rip_tab_ripped')) { 
     var events = [fireA, fireB]; 

     //declare counter 
     this.counter = this.counter || 0; // set to 0 if value is null 

     events[this.counter](); 
     this.counter = ++this.counter % 2; // You only have two methods 
    } 
});