2011-08-25 26 views
2

有一個問答系統,答案開始隱藏,然後當問題被點擊時,答案就會滑落。這工作正常,但我希望它,如果再次點擊問題,答案滑回。目前它只是忽略了這個命令。刪除/添加類正在工作,所以我不能認爲它可以是什麼?p標籤會滑落,但不會向上滑動

HTML: <h2 class="traverse">What subjects are covered in the Core Knowledge Sequence UK?</h2> <p class="traversing">The Core Knowledge Sequence UK is a guideline of the fundamental skills and content to cover in English, maths, history and geography, science, music and visual arts.</p>

的Jquery:

$(".traverse").click(function(){ 
      $(this).next("p.traversing").slideDown(); 
      $(this).removeClass('traverse'); 
      $(this).addClass('traversed'); 
     }); 

$(".traversed").click(function(){ 
      $(this).next("p.traversing").slideUp(); 
      $(this).removeClass('traversed'); 
      $(this).addClass('traverse'); 
     }); 

回答

3

訣竅是您在用戶操作添加穿越類...在將事件處理程序附加到與jQuery的所有匹配(因此,新的ele沒有抓到)

我建議改變方法。使用.toggle();

例如,可以切換可以切換的元素並上下滑動。

$('.collapsible').toggle(function(){ 
    $(this).next('p.traversing').slideUp(); 
    }, function(){ 
    $(this).next('p.traversing').slideDown(); 
    } 
); 

這裏有一個演示:http://jsfiddle.net/7aVkx/1/

1

不要附加click處理多次,而不是使用slideToggle()

$(".traverse").click(function(){ 
      $(this).next("p.traversing").slideToggle(); 
      $(this).removeClass('traverse'); 
      $(this).addClass('traversed'); 
     }); 
0

你可以做一個live click綁定。因爲您在加載後將此類添加到段落中,它不會找到對它的引用。

$(".traversed").live("click",function(){}); 

你有什麼理由要改變這個類嗎?一個替代方案可能是使用slideToggle()並單獨離開課程。

0

因爲您(在您的點擊處理程序中)不斷添加/刪除用於選擇要處理的元素的類,您將不得不使用.live。 正是這樣做:

$(".traverse").click(....) 

不「跟蹤」未來可能有「穿越」類元素。它應該工作,如果你會使用:

$(".traverse").live("click", ....) 
0
$('p.traversing').slideUp(); 
$(".traverse").click(function() { 
    $(this).removeClass('traverse').addClass('traversed'); 
    $(this).next("p.traversing").slideToggle(); 
}); 
$(".traversed").click(function() { 
    $(this).next("p.traversing").slideToggle(); 
    $(this).removeClass('traversed').addClass('traverse'); 
}); 
+0

你也可以使用'live'點擊事件 – thecodeparadox

0

你設置上.traversed類的所有元素的處理程序,但在那個時候your desired elements don't have that class

使用.live代替:*

$(".traverse").live('click', function(){ 
     $(this).next("p.traversing").slideDown(); 
     $(this).removeClass('traverse'); 
     $(this).addClass('traversed'); 
    }); 

$(".traversed").live('click', function(){ 
     $(this).next("p.traversing").slideUp(); 
     $(this).removeClass('traversed'); 
     $(this).addClass('traverse'); 
    }); 

Live demo.


*「說明:附上處理該事件對於當前選擇現在符合這所有的部件和在將來。」