中註冊兩個點擊事件我正在嘗試設置複選框列表的樣式。我已經添加了我的樣式,並且它們在呈現時正確顯示。我想在複選框的標籤被點擊時添加一個類。這是我的標記和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
您可以從標籤中取出輸入。看起來控件看起來是一樣的,你不會有這個問題 –