javascript JQuery .prop 函数无法取消复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15706443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery .prop function not working to uncheck box
提问by JasonBK
I tried many of the ideas I found here to uncheck a checkbox when a different checkbox is checked, but none are working ...
我尝试了在这里找到的许多想法,以在选中不同的复选框时取消选中复选框,但没有一个有效......
Right I now I have :
现在我有:
$("#chkBox1").click(function () {
if ($(this).is(":checked")) {
$('#chkBox2').prop('checked', false); }
});
..but no results, chkBox2 remains checked
..但没有结果,chkBox2 保持选中状态
here is a checkbox in HTML:
这是 HTML 中的复选框:
<input type="checkbox" name="art" id="chkBox1" data-mini="true" data-theme="c" />
one possible difference in my code is that the checkboxes are only added to the page when a button is clicked, using href...the checkboxes are in the HTML (not created in Javascript)..but are not visible until a button is clicked..may this be part of the problem? Or am I missing something else? Also, I am using JQuery Mobile.
我的代码中一个可能的区别是复选框仅在单击按钮时添加到页面中,使用 href ......复选框在 HTML 中(不是在 Javascript 中创建的)......但在单击按钮之前不可见..这可能是问题的一部分吗?还是我错过了其他东西?另外,我正在使用 JQuery Mobile。
回答by Omar
You need to refresh it after changing its' .prop
, using .checkboxradio('refresh')
.
您需要在更改其' 后刷新它.prop
,使用.checkboxradio('refresh')
.
// Check #chkBox2 by default
$('#chkBox2').prop('checked', true).checkboxradio('refresh')
// Uncheck #chkBox2 when #chkBox1 is checked
$('#chkBox1').on('click', function () {
if ($(this).is(':checked')) {
$('#chkBox2').prop('checked', false).checkboxradio('refresh');
}
});
回答by JasonBK
sorry, I should have kept reading!
对不起,我应该继续阅读!
this seems to do the trick:
这似乎可以解决问题:
$('#chkBox1').checkboxradio('refresh');
..but I am not exactly sure why, is this something unique to JQuery Mobile?
..但我不确定为什么,这是 JQuery Mobile 独有的东西吗?
回答by McRui
Html
html
<input type="checkbox" name="art" id="chkBox1" data-mini="true" data-theme="c" />
<input type="checkbox" name="art2" id="chkBox2" data-mini="true" data-theme="c" checked="checked" />
jQuery:
jQuery:
(function ($) {
$(document).ready(function () {
$("#chkBox1").click(function () {
if ($(this).is(":checked")) {
$('#chkBox2').prop('checked', false);
}
});
});
})(jQuery);
Working example here http://jsfiddle.net/SwmN6/75/
回答by Sjoerd
You are checking this
, and changing chkBox2
:
您正在检查this
和更改chkBox2
:
if ($(this).is(":checked")) {
$('#chkBox2').prop('checked', false); }
Try this instead:
试试这个:
if ($('#chkBox2').is(":checked")) {
$('#chkBox2').prop('checked', false); }
Or simply:
或者干脆:
$('#chkBox2').prop('checked', false);