[英]jquery uncheck and check and vise versa checkbox of child element
這是我的html
#This will be generated throught loop
<li class="selector">
<a>
<input type="checkbox" value="test" /> test
</a>
</li>
這是我的jquery點擊事件
$('.selector').on('click', function() {
if($(this).find('input').is(':checked')){
#uncheck the checkbox
}else{
#check the checkbox
}
});
如何取消選中是否選中以及如何選中未選中
嘗試
$(document).on('click', '.selector', function (e) {
if (!$(e.target).is('input')) {
$(this).find('input').prop('checked', function () {
return !this.checked;
});
}
});
演示: 小提琴
其他方式
$(document).on('click', '.selector', function (e) {
$(this).find('input').prop('checked', function () {
return !this.checked;
});
});
$(document).on('click', '.selector input', function (e) {
e.stopPropagation();
});
演示: 小提琴
嘗試這個
$('.selector').on('click', function() {
var checkbox = $(this).find(':checkbox');
if($(checkbox).is(':checked')){
$(checkbox).prop('checked', false);
}else{
#check the checkbox
$(checkbox).prop('checked', true);
}
});
我不明白您為什么要使用JavaScript來做到這一點。 如果用戶直接單擊復選框,它將自動對其進行檢查/取消選中,但是如果您在JS中添加代碼以對其進行檢查/取消選中,這將取消默認行為,因此在您的點擊處理程序中,您需要測試點擊是否.selector
其他位置。
Anwyay, .prop()
方法讓您了解了:
$('.selector').on('click', function(e) {
if (e.target.type === "checkbox") return; // do nothing if checkbox clicked directly
$(this).find("input[type=checkbox]").prop("checked", function(i,v) {
return !v; // set to opposite of current value
});
});
演示: http : //jsfiddle.net/N4crP/1/
但是,如果您的目標只是允許單擊文本“ test”以單擊該框,則不需要JavaScript,因為<label>
元素就是這樣做的:
<li class="selector">
<label>
<input type="checkbox" value="test" /> test
</label>
</li>
如您在本演示中所見: http : //jsfiddle.net/N4crP/2/-單擊文本“ test”或復選框將切換當前值而無需任何JavaScript。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.