2014-02-17 23 views
2

使用jsfiddle上給出的示例代碼,即單擊一個複選框取消選中所有其他複選框工作正常,但是當我將jquery版本更改爲1.10.1時,它不起作用,任何解決方案代碼不工作時,jQuery版本更改

$(".chb").each(function(){ 
     $(this).change(function(){ 
     $(".chb").attr('checked',false); 
     $(this).attr('checked',true); 
    }); 
    }); 

這裏是鏈接

http://jsfiddle.net/44Zfv/

+0

什麼時候開始什麼版本?我相信在1.6之後你應該使用'prop()'。 –

+0

如果你不能改變jQuery版本,你可以使用jQuery的遷移。 http://blog.jquery.com/2013/05/08/jquery-migrate-1-2-1-released/。如果你可以改變它,答案可以幫助你。 – sinanakyazici

回答

1

由於您沒有更改屬性,但該屬性使用jQuery的prop方法代替。這將版本工作屬性和屬性之間1.10+

$(".chb").each(function(){ 
    $(this).change(function(){ 
     $(".chb").prop('checked',false); 
     $(this).prop('checked',true); 
    }); 
}); 

差異

http://www.w3.org/TR/SVGTiny12/attributeTable.html

屬性一般是由在HTML中定義,而屬性是由DOM定義。對於某些元素,屬性和屬性反映相同(例如元素的ID)。展現DOM互動的一個好方法是:

<input type="text" value="some value"> 

這個元素有兩個屬性(typetext)。當瀏覽器解析文檔時,它將使用屬性typevalue爲此特定元素創建一個對象。如果您隨後在其中寫入內容,則會影響元素value屬性。你可以更好的看到區別嘗試檢索時value

input.getAttribute('value') // -> will return the inital value: "some value" 
input.value // -> will return the object's value property (the text you've entered) 
+0

你能解釋一個屬性和一個屬性之間的區別嗎?我知道我應該使用prop(),但我不太瞭解它的區別。 – Flater

+0

@Flater查看我的更新回答。 – enyce12

+0

感謝您的額外信息:) – Flater

1

嗨穆扎法爾試支撐,而不是ATTR

$(".chb").each(function() 
    { 
    $(this).change(function() 
    { 
    $(".chb").prop('checked',false); 
    $(this).prop('checked',true); 
    }); 
}); 
2

版本正在切換從1.5.2至1.10。在jQuery 1.6之後,推薦使用.prop()代替.attr()

$(".chb").each(function(){ 
    $(this).change(function(){ 
     $(".chb").prop('checked',false); 
     $(this).prop('checked',true); 
    }); 
}); 

更好的解決方案是使用單選按鈕,它會給你所需的行爲,而不需要任何額外的腳本。

<label><input type="radio" name="cb" class="chb" /> Radio1</label> 
<label><input type="radio" name="cb" class="chb" /> Radio2</label> 
<label><input type="radio" name="cb" class="chb" /> Radio3</label> 
<label><input type="radio" name="cb" class="chb" /> Radio4</label> 

JS小提琴:http://jsfiddle.net/44Zfv/292/