如何动态检查“复选框” - jQuery Mobile
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17027566/
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
How to check "checkbox" dynamically - jQuery Mobile
提问by Jonh Smid
With HTML a checkbox is created like this:
使用 HTML 创建一个复选框,如下所示:
<form>
<input type="checkbox" id="category1">Category1<br>
</form>
With javascript we can check the checkbox like this:
使用javascript,我们可以像这样检查复选框:
$("#category1")[0].checked = true
Now I am trying to create the same page with jquery-mobile. The checkbox looks like this:
现在我正在尝试使用 jquery-mobile 创建相同的页面。复选框如下所示:
<form>
<label>
<input name="checkbox-0 " type="checkbox">Check me
</label>
</form>
Why is there is no id
here? Is the name the id
? Should I delete the attribute name and create one with the name id
?
为什么这里没有id
?名字是id
?我应该删除属性名称并使用名称创建一个id
吗?
How can I check this checkbox here with Javascript/jQuery?
如何使用 Javascript/jQuery 在此处选中此复选框?
I tried the code above, but it doesn't seem to work for this checkbox.
我尝试了上面的代码,但它似乎不适用于此复选框。
回答by Omar
You need to refresh it after changing its' .prop
, using .checkboxradio('refresh')
. This is the correct way to check checkbox/radio in jQuery Mobile.
您需要在更改其' 后刷新它.prop
,使用.checkboxradio('refresh')
. 这是在 jQuery Mobile 中选中复选框/单选框的正确方法。
$('.selector').prop('checked', true).checkboxradio('refresh');
Reference: jQuery Mobile API
回答by tymeJV
You can do:
你可以做:
$('input[name="checkbox-0"]').prop("checked", true).checkboxradio('refresh'); //sets the checkbox
var isChecked = $('input[name="checkbox-0"]').prop("checked"); //gets the status