2016-01-21 38 views
0

我手動選中了使用.attr('checked', true);的單選按鈕(因爲prop('checked', true);在我的情況下似乎沒有做任何事情)。儘管將「checked」屬性設置爲「checked」,jQuery選中的單選按鈕仍未被檢查

雖然單選按鈕確實得到checked在標記屬性等於checked,單選按鈕還沒有選中(視覺上的頁面上,所有單選按鈕處於未選中狀態)。

這怎麼可能?

jQuery的:獲得

$('.variations_fieldset input[value="Every 2 months"]').attr('checked', true); 

HTML:

<fieldset class="variations_fieldset"> 
    <input type="radio" data-attribute_name="attribute_billing" name="attribute_billing" id="billing1" value="Once Off"> 
    <label for="billing1">Once Off</label> 
    <input type="radio" data-attribute_name="attribute_billing" name="attribute_billing" id="billing2" value="Every 1 month"> 
    <label for="billing2">Every 1 month</label> 
    <input type="radio" data-attribute_name="attribute_billing" name="attribute_billing" id="billing3" value="Every 2 months" checked="checked"> 
    <label for="billing3">Every 2 months</label> 
</fieldset> 
+0

請張貼一個完整的代碼示例。 – j08691

+0

你使用任何插件的單選按鈕像CSS樣式? –

+0

是的,但是CSS可以防止單選按鈕被查看,即使它確實被檢查過嗎? – drake035

回答

2

始終使用prop打底層元素的屬性,而不是attr

$('.variations_fieldset input[value="Every 2 months"]').prop('checked', true); 

attr只是改變DOM但確實並不總是設置基礎屬性。

請注意:prop不會更新attr,因此您無法在DOM檢查器中看到更改。

的jsfiddle:https://jsfiddle.net/e0tpgekm/1/

+1

OP說已經試過了。 – shawnt00

+1

屬性更改不會將「已選中」屬性添加到單選按鈕。 – Rycochet

+0

@ shawnt00:OP可能還沒有意識到,如果你使用prop,'attr'的改變在DOM中不可見。你不能總是在表面上看到這樣的表述。 –

-2

如果您使用jQuery 1.6之前的嘗試:

.attr('checked','checked'); 
相關問題