2016-06-10 22 views
1

這不是attr() VS prop()問題。jQuery的ATTR()方法的行爲

考慮具有這種這樣簡單的網頁形式:

<form action="/"> 
    <input type="radio" name="type" value="1" checked> 
    <input type="radio" name="type" value="2" > 
    <input type="radio" name="type" value="3" > 
    <input type="radio" name="type" value="4" > 
    <button type="submit"> Submit </button> 
</form> 

非常第一個單選按鈕具有checked屬性作爲其默認狀態下,開放該web表單帶來了一個公知的圖像:

enter image description here

在一個書面jQuery腳本文件中,我試圖檢查一個單選按鈕 - 但它可以使用prop()在一個正確和無頭痛的方式,我去了attr()

使用瀏覽器的控制檯,我能立即檢查結果:

enter image description here

enter image description here

但我知道檢查所需的一種期待正確的結果之前,我應該取消所有輸入:

enter image description here

enter image description here

的爭論從這裏開始,重複第一步的時候:

enter image description here

enter image description here

我的問題是,爲什麼出現這種情況?單選按鈕中沒有複選標記,並且在服務器端沒有任何價值。

+0

發佈你的jQuery代碼 –

+0

@AnkurBhadania這個簡單的例子是一個真實的例子,所給出的代碼。但是沒有'.js'文件。 – revo

+0

您使用的是什麼版本的jQuery? – putvande

回答

0

問題是jQuery特定版本。這不是一個錯誤,也沒有隨jQuery v3 alpha發佈一起發佈。

不過後來,從jQuery v3 beta版本開始,removeAttr()改了一點。

在jQuery中< 3. *removeAttr()方法設置動態/電流狀態爲false:

// Set corresponding property to false 
if (getSetInput && getSetAttribute || !ruseDefault.test(name)) { 
    elem[ propName ] = false; 

而在療法另一側attr()僅設置默認狀態(未當前狀態)。但在jQuery > = 3.0,我們不再看到這些行。

除v3以外的所有版本。*(>最終和beta版),我們不能從這兩行預計,檢查單選按鈕:

$('input[name="type"]').removeAttr('checked'); 
$('input[value="3"]').attr('checked', true); 

但是這三條線一起工作對方:

$('input[name="type"]').removeAttr('checked'); 
$('input[value="3"]').attr('checked', true); 
$('input[value="3"]').prop('checked', true); 

或者更簡單:

$('input[name="type"]').removeAttr('checked'); 
$('input[value="3"]').prop('checked', true); 

(但要注意,一些JavaScript代碼可以檢查屬性,而不是屬性所以,你必須做一個額外的.atrr()。)

此外,在早期版本中,它更最好不要使用removeAttr()不惜一切,但只有attr()像這樣:

$('input[name="type"]:checked').attr('checked', false); 
$('input[type="3"]').attr('checked', true); 

此的removeAttr()行爲的改變是在Github以及討論。

感謝那些評論這個問題的人。