2013-05-21 31 views
0

我想要實現的是: jQuery的。點擊()不點火的預期

  • 用戶點擊一個H4格。提問
  • 。提問的div擴大到90像素內,和它的子段滑入視圖通過將其margin-top設置爲0
  • 當用戶第二次單擊h4元素時,.question div應該返回到35px高度,並且該段落應該將margin-top設置爲35px。

Here's a Fiddle

jQuery(document).ready(function($) { 
    $('.question h4').click(function() { 
     $(this).parents('.question').css('height', '90'); 
     $(this).siblings('p').css('margin-top', '0'); 
     $(this).parent().addClass('open'); 
    }); 

    $('.question.open h4').click(function() { 
     $(this).parent.removeClass('open'); 
     $(this).parents('.question').css('height', '65px'); 
     $(this).siblings('p').css('margin-top', '35px'); 
    }); 
}); 
+0

Typo? '$(this).parent'?同時檢查這個http://api.jquery.com/end/將幫助鏈接所有這些方法。 – elclanrs

+1

第一次點擊事件將始終適用於這兩種情況!使用一個處理程序並檢查狀態! – epascarello

回答

1

你真的只需要一個處理程序:

$('.question h4').click(function() { 
    if ($(this).is('.open h4')) { 
     $(this).parent.removeClass('open'); 
     $(this).parents('.question').css('height', '65px'); 
     $(this).siblings('p').css('margin-top', '35px'); 
    } 
    else { 
     $(this).parents('.question').css('height', '90'); 
     $(this).siblings('p').css('margin-top', '0'); 
     $(this).parent().addClass('open'); 
    } 
}); 

你的第二個處理程序分配什麼也不做,因爲沒有你的<h4>元素開始與「開放」級(或者,至少,我懷疑他們別)。

+0

哇。我不知道我怎麼錯過了...謝謝!自從你指出爲什麼它沒有被解僱之後,我將把它標記爲答案。 – mchandleraz

+0

@mchandleraz好吧我現在對'.is()'測試做了一個小修改 – Pointy

4

你第一次點擊處理程序被燒成即使.question.open。您需要從第一個選擇器中排除.open

$('.question:not(.open) h4').click(... 
+3

這個答案不正確。 「.open」處理程序對於所有沒有「.open」類的「

」元素將如何工作? – Pointy

+0

謝謝。稍作修改 –

+0

這一切都沒有任何意義。你需要綁定到所有的元素,然後檢查他們是否擁有這個類,或者使用事件委託,但這是不必要的。保持OP的方式,綁定到兩個不同的選擇器(即使你「修復」選擇器),將不起作用 – Ian

2

正如Pointy所提到的,您只需要一個帶有條件語句的處理程序。另外,爲了速度,開銷和簡單性,我會考慮將節點上所有需要的操作串成一行(即,任何你想對$(this).parent()進行的操作都應該串在一起,這樣jQuery只需要解析DOM一次)。

$('.question h4').click(function() { 
    if (!$(this).parent().hasClass('open')){ 
     $(this).parents('.question').css('height', '90').addClass('open'); 
     $(this).siblings('p').css('margin-top','0'); 
    }else{ 
     //$(this).parents('.question').css('height', '65px'); 
     $(this).parent().css('height', '65px').removeClass('open'); 
     $(this).siblings('p').css('margin-top', '35px'); 
    } 
}); 
+0

這是我知道我做了一段時間錯誤的事情,但並沒有打算找出正確的方法來做的東西。謝謝(你的)信息。我會很快重寫我的jQuery的一些:) – mchandleraz