[英]jQuery .click() doesn't seem to actuate the unchecking of radio boxes
我試圖在單選框上動態創建一個重置按鈕,然后說重置按鈕在用戶單擊按鈕時取消選中任何現有的選擇,但是當我單擊它時,什么也沒有發生。 我可能缺少明顯的東西,但不確定。
$('.surveyor_radio').parent().parent().append('<div class="reset-button">A reset button</div>');
$('.reset-button').click(function () {
$('#form input[type="radio":checked]').each(function () {
$(this).prop('checked', false);
});
});
$('fieldset').each(function () {
var qid = $(this).attr('id');
$('.reset-button', $(this)).attr('data-question-id', qid);
});
更換
$('#form input[type="radio":checked]')
同
$('#form input[type="radio"]:checked')
但是,請注意,您的代碼不會區分單選按鈕組,只會取消選中整個表單中的所有單選按鈕。
幸運的是,您已經在單選按鈕上存儲了data-question-id
,因此我們可以使用它來提供上下文,而不是#form
:
$('.reset-button').click(function () {
$('input[type="radio"]:checked','#'+$(this).data('question-id')).each(function () {
$(this).prop('checked', false);
});
});
http://jsfiddle.net/mblase75/sFUBV/10/
正如nzifnab所指出的,我們甚至可以進一步簡化:
$('.reset-button').click(function () {
$('input[type="radio"]','#'+$(this).data('question-id')).prop('checked', false);
});
您不想使用removeAttr
, prop
方法就足夠了。
您不必使用.each
,因為大多數在jquery集合上調用的jquery方法將已經在所述集合的每個對象上執行。
這有效: http : //jsfiddle.net/sFUBV/14/
$('.surveyor_radio').parent().parent().append('<div class="reset-button">A reset button</div>');
$('.reset-button').on('click', function () {
$(this).
closest('li.input').
find('input[type=radio]').
prop('checked', false);
});
沒有理由添加:checked
選擇器,因為無論如何您都取消選中它們,如果您取消選中未選中的選擇器又有什么關系呢? 兩種情況都會發生相同的事情。
另請注意,您不一定必須按照接受的答案所指示的問題ID進行操作。 這只是查看當前li.input
中的所有單選按鈕,因此您可以在任何地方使用它,而不必擔心問題ID和插值廢話。
另外,您應該使用on
綁定事件,而不是click
或live
這有效:
$("input[type='radio']:checked").each(function () {
$(this).removeAttr('checked');
});
檢查小提琴: http : //jsfiddle.net/sFUBV/9/
試試這行而不是each()函數
$('.reset-button').click(function () {
$('#form input[type="radio"]:checked').prop('checked', false);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.