如何动态检查“复选框” - 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:17:14  来源:igfitidea点击:

How to check "checkbox" dynamically - jQuery Mobile

javascriptjqueryhtmljquery-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 idhere? 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 中选中复选框/单选框的正确方法。

Demo

演示

$('.selector').prop('checked', true).checkboxradio('refresh');

Reference: jQuery Mobile API

参考: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

回答by blend

Straight from the jQ Mobile docs:

直接来自jQ Mobile 文档

$("input[type='checkbox']").attr("checked",true);