2011-12-17 72 views
0

我有這樣的HTML:覆蓋jQuery的。點擊事件

<style> 
div.icons { 
    background-color:red; 
    width:100px; 
    height:100px; 
    float:left; 
    margin-right:10px; 
} 
</style> 

<div class="icons"><input type="checkbox" checked="checked" />Box 1</div> 
<div class="icons"><input type="checkbox" checked="checked" />Box 2</div> 
<div class="icons"><input type="checkbox" checked="checked" />Box 3</div> 

而這個jQuery ...

<script> 
$(document).ready(function() { 
    $("div.icons").click(
     function(){ 
      if ($(this).children("input").is(":checked")) { 
       $(this).css("background-color","yellow"); 
       $(this).children("input").attr('checked', false); 
      } else { 
       $(this).css("background-color","red"); 
       $(this).children("input").attr('checked', true); 
      } 
     } 
    ); 

}); 
</script> 

當我點擊一個div,jQuery的改變的背景顏色該div並取消選中它的內部輸入。但是當我點擊div內的輸入複選框時,它不會檢查輸入框。

當點擊複選框時,有沒有辦法覆蓋$("div.icons").click?還是有更好的方法來做到這一點?

回答

4

我會做這樣的事情。我認爲代碼要簡單得多。

  1. 使用類來管理顯示。您可以使用jQuery的toggleClass函數來切換類。
  2. 使用jQuery的.trigger啓動對每個div的輸入元素的點擊
  3. 防止點擊輸入從創建無限循環傳播。

http://jsfiddle.net/4hLrF/

div.icons { 
    background-color:red; 
    width:100px; 
    height:100px; 
    float:left; 
    margin-right:10px; 
} 

div.checked { 
    background: yellow; 
} 

$('input').click(function(e) { 
    $(this).parent().toggleClass('checked'); 
    e.stopPropagation(); 
}); 

$('div').click(function() { 
    $(this).children('input').trigger('click'); 
}); 
+0

不錯,謝謝! – supercoolville 2011-12-17 06:25:50

4

是啊,如果你添加event.stopPropagation()爲複選框元素click事件處理程序,你可以從沸騰起來的複選框的父母停止click事件:

$('.icons').children().on('click', function (event) { 
    event.stopPropagation(); 
}); 
3

這裏是另一種方式來覆蓋jQuery的單擊事件:

$('div').unbind('click').on('click', '.icons', function (event) { 
    event.stopPropagation(); 
}); 

它爲我工作。