2009-05-19 31 views
4

有人可以幫我解決這個問題。有HTML代碼:如何從點擊事件中分配子元素

<h3> 
    <label> 
     <input type="checkbox" name="country" value="us" /> United States 
    </label> 
</h3> 
<p>Some content goes here</p> 

我想通過點擊H3標籤切換p元素,但我不wan't切換,如果我點擊了標籤上

$('h3').click(function() { 
    // Does something goes here? 
    $(this).next('p').toggle(); 
} 
+0

爲什麼不呢? p中的內容是否與您正在切換的複選框連接? – cgp 2009-05-19 13:42:39

+0

我假設標籤是指實際的文本,而不是HTML元素。 – tvanfosson 2009-05-19 13:44:40

回答

17

您需要檢查行動的目標

$('h3').click(function(e) { 
    // if they clicked the h3 only 
    if (this == e.target) { 
    $(this).next('p').toggle(); 
    } 
} 

altCognito的建議也可以工作,但它是更多的代碼。

2

你想stopPropagation()

$('h3').click(function() { 
    // Does something goes here? 
    $(this).next('p').toggle(); 
} 
$('label').click(function(e) { 
    e.stopPropagation(); 
} 
相關問題