中注册两个点击事件我正在尝试设置复选框列表的样式。我已经添加了我的样式,并且它们在呈现时正确显示。我想在复选框的标签被点击时添加一个类。这是我的标记和here is the same in a jsfiddle。您可以从我的小提琴中看到,只需点击一次即可注册两个点击事件。为什么?为什么在这个html/css/jquery
HTML:
<ul>
<li>
<label for="test_0" class="">
<input id="test_0" name="offering_cycle" type="checkbox" value="1"> Fall
</label>
</li>
<li>
<label for="test_1" class="">
<input id="test_1" name="offering_cycle" type="checkbox" value="2"> Spring
</label>
</li>
<li>
<label for="test_2" class="">
<input id="test_2" name="offering_cycle" type="checkbox" value="3"> Summer
</label>
</li>
<li>
<label for="test_3" class="">
<input id="test_3" name="offering_cycle" type="checkbox" value="4"> Other
</label>
</li>
</ul>
CSS:
ul {
list-style-type:none;
}
label {
position:relative;
display:inline-block;
padding-left:27px;
height:25px;
}
label:before {
display:block;
position:absolute;
top:-2px;
margin-left:-28px;
width:18px;
height:18px;
background-color:#fff;
border-radius:5px;
border:1px solid #ccc;
text-align: center;
color:#fff;
font-size:18px;
content:'a';
}
input {
width:1px;
height:1px;
border:0;
opacity:0;
float:right;
}
的jQuery:
$('label[for*=test_]').on('click',function(){
$(this).toggleClass('testing');
});
您将单击事件绑定到标签,但如果有人单击标签内的某个元素,它可能会创建两个点击事件。一个用于子元素,另一个用于父元素。 –
@b_dubb正是我的想法。我相信它也会为输入生成一个点击事件! – Michelangelo
您可以从标签中取出输入。看起来控件看起来是一样的,你不会有这个问题 –