2012-03-20 51 views
1

我有一個問題,當我點擊鏈接p打開,然後點擊另一個鏈接它不起作用。它在我再次點擊時起作用。JQuery切換()函數

這是我的jQuery代碼:

var toggle = 0; 
$(document).ready(function() { 
    $(".feedback_block").each(function() { 
     $("a", this).click(function (e) { 
      if (toggle == 0) { 
       $(this).parent().children("p").stop(true, true).fadeIn(500); 
       $(this).addClass("clicked"); 
       $(this).children().addClass("clicked_span"); 
       toggle = 1; 
       console.log(toggle); 
      } else 
      if (toggle == 1) { 
       $(this).parent().children("p").stop(true, true).fadeOut(500); 
       $(this).removeClass("clicked"); 
       $(this).children().removeClass("clicked_span"); 
       toggle = 0; 
       console.log(toggle); 

      } 
      e.stopPropagation(); 
      return false; 
     }); 
     toggle = 0; 
    }); 
}); 

當我點擊參數切換獲得1,當我點擊另一個鏈接的初始值應爲0。我該怎麼辦呢?

我的例子:http://jsfiddle.net/amkrtchyan/tjzaR/

+0

我編輯過這個,但是S/O編輯器拒絕了大約10個建議的標題(真氣)。任何人,請改進我的(即將發佈的)編輯。 – halfer 2012-03-20 10:38:29

回答

1

你可以簡單地使用切換()(http://jsfiddle.net/tjzaR/2/)

$(document).ready(function() { 
    $(".feedback_block").each(function() { 
     $("a", this).toggle(function (e) { 

       $(this).parent().children("p").stop(true, true).fadeIn(500); 
       $(this).addClass("clicked"); 
       $(this).children().addClass("clicked_span"); 

      }, function(){ 
       $(this).parent().children("p").stop(true, true).fadeOut(500); 
       $(this).removeClass("clicked"); 
       $(this).children().removeClass("clicked_span"); 


      }); 
    }); 
}); 

,或者你可以做(​​小提琴這裏http://jsfiddle.net/tjzaR/1/

$(".feedback_block").each(function() { 
    $("a", this).click(function (e) { 
     if (!$(this).parent().children("p").is(":visible")){ 
      $(this).parent().children("p").stop(true, true).fadeIn(500); 
      $(this).addClass("clicked"); 
      $(this).children().addClass("clicked_span"); 

     } else{ 
      $(this).parent().children("p").stop(true, true).fadeOut(500); 
      $(this).removeClass("clicked"); 
      $(this).children().removeClass("clicked_span"); 


     } 
     return false; 
    }); 

}); 
+0

我知道函數toggle(),但是有一種方法可以在我的代碼中執行此操作? – 2012-03-20 10:30:11

+0

@AramMkrtchyan只需刪除你的'$(「a」,this).click(function(e){'用上面的代碼,並刪除你創建的切換變量。 – voigtan 2012-03-20 10:35:55

+0

感謝您的幫助:) – 2012-03-20 10:39:01

0
$("a", this).toggle(function() { 

       $(this).parent().children("p").stop(true, true).fadeIn(500); 
       $(this).addClass("clicked"); 
       $(this).children().addClass("clicked_span"); 
       return false; 

      }, function(){ 

       $(this).parent().children("p").stop(true, true).fadeOut(500); 
       $(this).removeClass("clicked"); 
       $(this).children().removeClass("clicked_span"); 
       return false; 

      }); 

難道我們不能直接使用切換功能。 Toggle

+0

,但有一種方法可以在我的代碼中執行此操作? – 2012-03-20 10:33:32