2011-12-17 77 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(); 
}); 

它为我工作。