jQuery爲radio賦值

問題:表單clear後,radio賦值無效。去除clear後卻可:我用的以下方法嘗試,都失敗,用末尾方法實現了。

以下方法

//取radio的值
    $("input[name='radioName'][checked]").val(); 
    //給radio 賦值, 選中值爲2的radio:
    $("input[name='radioName'][value=2]").attr("checked",true); 

官方的方法是這樣寫:

 //獲取選中值,三種方法都可以:
    $('input:radio:checked').val();
    $("input[type='radio']:checked").val();
    $("input[name='rd']:checked").val();
    //設置第一個Radio爲選中值:
        $('input:radio:first').attr('checked', 'checked');
    //或者
    $('input:radio:first').attr('checked', 'true');
    //注:attr("checked",'checked')= attr("checked", 'true')= attr("checked", true)
    //設置最後一個Radio爲選中值:
    $('input:radio:last').attr('checked', 'checked');
    //或者
    $('input:radio:last').attr('checked', 'true');
    //根據索引值設置任意一個radio爲選中值:
    $('input:radio').eq(索引值).attr('checked', 'true');索引值=0,1,2....
    //或者
    $('input:radio').slice(1,2).attr('checked', 'true');
    //根據Value值設置Radio爲選中值
    $("input:radio[value=http://www.2cto.com/kf/201110/'rd2']").attr('checked','true');
    //或者
    $("input[value=http://www.2cto.com/kf/201110/'rd2']").attr('checked','true');
    //刪除Value值爲rd2的Radio
    $("input:radio[value=http://www.2cto.com/kf/201110/'rd2']").remove();
    //刪除第幾個Radio
    $("input:radio").eq(索引值).remove();索引值=0,1,2....
    如刪除第3個Radio:$("input:radio").eq(2).remove();
    //遍歷Radio
    $('input:radio').each(function(index,domEle){
         //寫入代碼
    });

   此方法有效:   

$("input[name='GENDER'][value=" + object.GENDER + "]").prop("checked", "checked");//object..是請求得到的數據
$("input[name='MARRIAGE'][value=" + object.MARRIAGE + "]").prop("checked", "checked");
$("input[name='JOBTYPE'][value=" + object.JOBTYPE + "]").prop("checked", "checked");


總結:

    對於HTML元素本身就帶有的固有屬性,在處理時,使用prop方法。
    對於HTML元素我們自己自定義的DOM屬性,在處理時,使用attr方法

舉一個例子:

<input id="chk1" type="checkbox" />是否可見
<input id="chk2" type="checkbox" checked="checked" />是否可見

像checkbox,radio和select這樣的元素,選中屬性對應“checked”和“selected”,這些也屬於固有屬性,因此需要使用prop方法去操作才能獲得正確的結果。

$("#chk1").prop("checked") == false
$("#chk2").prop("checked") == true

如果上面使用attr方法,則會出現:

$("#chk1").attr("checked") == undefined
$("#chk2").attr("checked") == "checked"


————————————————
原文鏈接:https://blog.csdn.net/u013475983/java/article/details/72688555

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章