2012-01-14 63 views
1

首先,對不起我的英文不好。用onClick複選框覆蓋parrents onClick事件?

我在製作優惠券網站,並且無法選擇和取消選擇優惠券。每張優惠券都位於一個DIV「盒子」中,其中有一個複選框。

我在DIV框上做了一個onClick函數(所以用戶可以通過點擊DIV框內的任何東西來選擇優惠券,現在我需要的是,當用戶想要取消選擇優惠券時(通過點擊複選框在DIV框中),我需要'覆蓋'DIV的onClick函數(執行onClick事件的checkbox,而不是DIV的onClick事件)

我知道每個人都喜歡一些代碼作爲例子,但問題/問題很簡單,我不認爲你需要所有的事件/功能我un'useless代碼:)

謝謝:)

+2

代碼樣本幾乎總是幫助更容易。話雖如此,你有沒有考慮過在複選框上使用jQuery的stopPropagation? http://api.jquery.com/event.stopPropagation/ – j08691 2012-01-14 22:40:27

回答

2

好像你想要stopPropagation如果複選框被取消選中:http://jsfiddle.net/8Dcq8/

$("div").click(function() { 
    alert("add"); // clicking anywhere in div to add coupon 
}); 

$(":checkbox").click(function(e) { 
    if(!this.checked) { // if unchecking, remove coupon 
     alert("remove"); 
     e.stopPropagation(); // don't run parent onclick 
    } 
}); 
+1

呃,沒有。 '$(this).is(「:checked」)'完全過分。 [所有你需要的是'this.checked'](http://stackoverflow.com/a/4652402/139010)。 – 2012-01-14 22:43:20

0

你必須取消冒泡。有關說明,請參閱here

1

如果<div>單擊處理看起來是這樣的:

var $boxes = $('div.box'); 
$boxes.on('click', function() 
{ 
    // do whatever to select the coupon 
}); 

然後複選框處理程序應該是這個樣子:

$boxes.find('input[type="checkbox"]').on('click', function (event) 
{ 
    event.stopPropagation(); 
    // do whatever to deselect the coupon 
}); 

event.stopPropagation()

0

您可以使用jQuery替代方法,或者使用onClicks創建子元素,這些子元素不會針對您的複選框。你也許可以使用類似的東西。

document.getElementById('element').checked.onreadystatechange=function(){ 
//code 

} 

好運