[英]Why doesn't .attr(“checked”, true) work in Jquery 1.7 and up
這段代碼適用於jQuery,ver。 1.6
<input type="checkbox" class="radio" value="1" name="sameName" />
<input type="checkbox" class="radio" value="1" name="sameName" />
<input type="checkbox" class="radio" value="1" name="sameName" />
$("input:checkbox").click(function() {
if ($(this).attr("checked") === true) {
var group = "input:checkbox[name='" + $(this).attr("name") + "']";
$(group).attr("checked", false);
$(this).attr("checked", true);
} else {
$(this).attr("checked", false);
}
});
但是如果我使用jQuery 1.7的新方法更改代碼它不會工作? 為什么? 謝謝你的時間:
$("input:checkbox").on('click', function() {
if ($(this).attr("checked") === true) {
var group = "input:checkbox[name='" + $(this).attr("name") + "']";
$(group).attr("checked", false);
$(this).attr("checked", true);
} else {
$(this).attr("checked", false);
}
});
使用.prop('checked',true)
代替.attr
。
另外, if ($(this).attr("checked") === true)
可以縮短為簡單
if ($(this).prop("checked")) {
attr返回一個字符串。 您應該使用.prop為jQuery 1.6+設置checked屬性
$("input:checkbox").on('click', function() {
if (this.checked) {
var group = "input:checkbox[name='" + $(this).attr("name") + "']";
$(group).prop("checked", false);
$(this).prop("checked", true);
} else {
$(this).prop("checked", false);
}
});
來自jQuery .prop()docs
應該使用.prop()方法來設置disabled和checked而不是.attr()方法。
因為你的代碼錯了。 .on()事件需要容器的元素。
所以你的HTML代碼應如下所示:
<div id="chkContainer">
<input type="checkbox" class="radio" value="1" name="sameName" />
<input type="checkbox" class="radio" value="1" name="sameName" />
<input type="checkbox" class="radio" value="1" name="sameName" />
</div>
和JAVASCRIPT函數是這樣的:
$('#chkContainer').on('click', 'input:checkbox', function() {
if ( $(this).is(':checked') ) {
var group = "input:checkbox[name='" + $(this).attr("name") + "']";
$(group).attr("checked", false);
$(this).attr("checked", true);
} else {
$(this).attr("checked", false);
}
});
這是一個例子: http : //jsfiddle.net/5xDzv/1/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.