【问题标题】:How to check "checkbox" dynamically - jQuery Mobile如何动态检查“复选框” - jQuery Mobile
【发布时间】:2013-06-10 15:34:09
【问题描述】:

使用 HTML 创建一个复选框,如下所示:

<form>
   <input type="checkbox" id="category1">Category1<br>
</form>

使用 javascript,我们可以像这样检查复选框:

$("#category1")[0].checked = true

现在我正在尝试使用 jquery-mobile 创建相同的页面。复选框如下所示:

<form>
    <label>
        <input name="checkbox-0 " type="checkbox">Check me
    </label>
</form>

为什么这里没有id?名字是id吗?我应该删除属性名称并创建一个名称为id 的属性名称吗?

如何使用 Javascript/jQuery 在此处选中此复选框?

我尝试了上面的代码,但它似乎不适用于此复选框。

【问题讨论】:

标签: javascript jquery html jquery-mobile


【解决方案1】:

您需要在更改其'.prop 后使用.checkboxradio('refresh') 刷新它。这是在 jQuery Mobile 中检查复选框/收音机的正确方法。

Demo

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

参考:jQuery Mobile API

【讨论】:

  • 奥马尔一如既往的完美答案。非常感谢先生。
  • @JonhSmid 谢谢你,放轻松,伙计 :)
  • 谢谢!还有,为什么?!?!啊,根据文档:api.jquerymobile.com/checkboxradio/#method-refresh
  • 即使在链接的演示页面中,我也会收到错误 Uncaught Error: cannot call methods on checkboxradio prior to initialization; attempted to call method 'refresh'。请参阅我的答案,了解我是如何工作的。
  • @SharpC 将其包装在 pagecreate 事件中。您在小部件初始化之前调用了refresh
【解决方案2】:

你可以这样做:

$('input[name="checkbox-0"]').prop("checked", true).checkboxradio('refresh'); //sets the checkbox
var isChecked =  $('input[name="checkbox-0"]').prop("checked"); //gets the status

【讨论】:

  • 如果我给复选框一个 id 是正确的:$(#id_name).prop("checked", true); ?
  • 是的,不要忘记选择器中的引号$("#id_name").prop("checked", true);
  • @JonhSmid -- 不知道,我已经更新了我的答案。感谢您指出这一点!
【解决方案3】:

直接来自jQ Mobile docs

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

【讨论】:

  • $("input[type='checkbox']").attr("checked",true).checkboxradio("refresh");就在那儿!
【解决方案4】:

使用@Omar 的解决方案,我得到了错误:

未捕获的错误:无法在初始化之前调用 checkboxradio 上的方法;试图调用方法“刷新”

我其实有一个flipswitch checkbox

<div class="some-checkbox-area">
    <input type="checkbox" data-role="flipswitch" name="flip-checkbox-lesson-complete"
           data-on-text="Complete" data-off-text="Incomplete" data-wrapper-class="custom-size-flipswitch">
</div>

发现the solution是:

$("div.ui-page-active div.some-checkbox-area div.ui-flipswitch input[type=checkbox]").attr("checked", true).flipswitch( "refresh" ) 

备注

  • 我通常不为页面内容指定 id,因为 jQuery Mobile 将多个 div.ui-page 内容加载到单个 HTML 页面中以提高性能。因此,如果id 在 HTML body 中出现多次,我从来没有真正理解如何使用它(也许有人可以澄清这一点)。
  • 如果我使用prop 而不是attr,开关将进入无限翻转循环!我没有进一步调查...

【讨论】:

猜你喜欢
  • 2014-04-26
  • 2017-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多