簡體   English   中英

帶有html屬性“ checked”的不可檢查的單選按鈕

[英]uncheckable radio buttons with html attribute 'checked'

我正在使用#javascript中友好的家伙提供的以下簡單腳本來取消選中單選按鈕:

 $('.feed').on('click', 'input[type=radio]', function() {
    var myParent = $(this).closest('div');
  var ref = $(this);
  if( myParent.data('val') == $(this).val() ){
    var ref = myParent.find('.none input');
    ref.prop('checked',true);
  }
    myParent.data('val',ref.val() )
 });

一切正常,請參見此小提琴 ,但是當我將“ checked”屬性添加到一個單選按鈕時,實際上您必須單擊兩次,然后才能取消選中它,請參見此小提琴 這讓我思考,將'checked'設置為屬性實際上等於手動檢查單選按鈕嗎? 還是為什么我沒有通過?

這與添加屬性與單擊無關,這是附加的代碼,特別是以下行:

if (myParent.data('val') == $(this).val() ){

也就是說,如果您之前單擊過此按鈕,則將其關閉。

但是 ,您並不是在告訴代碼您已經(實際上)“單擊”了它。

您可以通過將初始值添加到“ myParent”中來實現,一種方法是將其添加到html中:

<div data-val='1'>

更新的小提琴: https : //jsfiddle.net/8jh2k8u8/4/


一種替代方法是通過找到選定的單選( :checked )通過代碼初始化父代:

var startup = $(".feed input[type=radio]:checked").first();
if (startup.length) {
    startup.closest("div").data("val", startup.val())
}

更新的小提琴: https : //jsfiddle.net/8jh2k8u8/5/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM