重写Jquery。单击事件
我有这个HTML:重写Jquery。单击事件,jquery,Jquery,我有这个HTML: <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> <
<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>
分区图标{
背景色:红色;
宽度:100px;
高度:100px;
浮动:左;
右边距:10px;
}
方框1
方框2
方框3
这个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>
$(文档).ready(函数(){
$(“div.icons”)。单击(
函数(){
如果($(this).children(“输入”)为(“:选中”)){
$(this.css(“背景色”、“黄色”);
$(this).children(“input”).attr('checked',false);
}否则{
$(this.css(“背景色”、“红色”);
$(this).children(“input”).attr('checked',true);
}
}
);
});
当我单击一个div时,jquery会更改该div的背景色,并取消选中其中的输入。但是,当我单击div内部的输入复选框时,它不会选中输入框
是否有方法覆盖
$(“div.icons”)。单击复选框时单击?或者有更好的方法吗?是的,如果将事件.stopPropagation()
添加到复选框元素的单击事件处理程序,则可以阻止单击事件冒泡复选框的父项:
$('.icons').children().on('click', function (event) {
event.stopPropagation();
});
我会这样做。我认为代码要简单得多
使用类来控制显示。可以使用jQuery的toggleClass函数切换类
使用jQuery的.trigger启动对每个div的输入元素的单击
防止单击输入的传播创建无限循环
下面是覆盖jQuery单击事件的另一种方法:
$('div').unbind('click').on('click', '.icons', function (event) {
event.stopPropagation();
});
这对我有用
$('div').unbind('click').on('click', '.icons', function (event) {
event.stopPropagation();
});