[英]change radio button state when parent is clicked
我有這個標記:
<div class='A'>
<input type='radio' name='B' class='B' />
</div>
<div class='A'>
<input type='radio' name='B' class='B' />
</div>
<div class='A'>
<input type='radio' name='B' class='B' />
</div>
所需的功能是 select 收音機通過單擊父div
或收音機輸入本身,如果已選中收音機,則單擊父級將無效,即返回 false。
我已經讓它在點擊父母時改變,但是當我點擊單選按鈕時,什么也沒有發生。 我的方法有什么問題?
jQuery:
$('input:radio').closest('div').on('click', function (e) {
if ($('input:radio', this).prop('checked') === true) {
console.log("returning false");
return false;
}
$('input:radio', this).prop('checked', true);
console.log("Clicked : " + $(this).attr('class'));
});
我可以建議使用label
元素而不是div
嗎? 您將獲得相同的行為,並且根本不需要 javascript。 CSS 將負責外觀。 我在你的小提琴中做了一個簡單的改變,效果很好。
$('.A').on('click', function (e) {
if ($(e.target).is('.B')) {
e.stopPropagation();
// So that event does not bubble when radio is selected
} else {
if ($('input:radio', this).prop('checked') === true) {
console.log("returning false");
return false;
}
$('input:radio', this).prop('checked', true);
}
console.log("Clicked : " + $(e.target).attr('class'));
});
您的代碼的問題是您在單擊復選框時返回 false 。 所以你間接地做event.preventDefault()
和event.stopPropagation()
做return false;
只有在單擊 div 時,您才明確需要將選中的屬性設置為 true。 但是,當您單擊收音機時,它會執行默認操作。 所以你需要停止事件的傳播。
e.preventDefault();
禁用radio
按鈕click
事件
$('input:radio').closest('div').on('click', function (e) {
$('input:radio', this).prop('checked', true);
});
單選按鈕的click
事件正在冒泡到div
,因此在這兩種情況下都會觸發回調。 問題是您正在阻止默認操作,在單選按鈕的情況下,它是否被選中。
如果單擊的元素是單選按鈕,您可以添加一個退出回調的條件:
$('input:radio').closest('div').on('click', function (e) {
if ($(e.target).is('input')) {
return;
}
if ($('input:radio', this).prop('checked') === true) {
console.log("returning false");
return false;
}
$('input:radio', this).prop('checked', true);
console.log("Clicked : " + $(this).attr('class'));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.