【问题标题】:How to programmatically refresh a group of radio buttons in jQuery Mobile?如何以编程方式刷新 jQuery Mobile 中的一组单选按钮?
【发布时间】:2014-03-29 03:10:35
【问题描述】:

假设我有一组像这样的 3 个单选按钮:

<label for="a-1">A</label>
<input type="radio" name="a" id="a-1" value="1" />
<label for="a-2">A</label>
<input type="radio" name="a" id="a-2" value="2" />
<label for="a-3">A</label>
<input type="radio" name="a" id="a-3" value="3" />

第一个收音机设置为checked="true"ala

$("input").eq(0).attr("checked", true);

JQM API for checkboxradio 表示如下:

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

以编程方式设置单选按钮。

问题
如果我需要将收音机从一个按钮切换到另一个按钮怎么办?所以....

$("input").eq(1).trigger("click");

是否总是需要在我的点击处理程序上单独更新我的单选按钮,还是不应该开箱即用?毕竟,当我有一个非 JQM 单选按钮组并触发单击单选元素时,之前选中的按钮会自动取消选中。

谢谢!

编辑:
简单的例子:

 var foo = '<input type="radio" checked="checked" name="a" id="a-1" value="1" />'  + 
           '<input type="radio" name="a" id="a-2" value="2" />' +
           '<input type="radio" name="a" id="a-3" value="3" />';
 $("div.ui-content").append( $(foo) );
 $(document.getElementById("a-2")).trigger("click");

这会生成三个单选按钮,第一个被选中。点击后,第二个收音机被选中而第一个未被选中。

编辑
JQM 示例:

$("div.ui-content").empty()
var bar = '<div data-role="controlgroup">' +
      '<input type="radio" name="a" id="a-1" value="choice-1" checked="checked">' + 
      '<label for="a-1">1</label>' +
      '<input type="radio" name="a" id="a-2" value="choice-2">' +
      '<label for="a-2">2</label>' +
      '<input type="radio" name="a" id="a-3" value="choice-3">' +
      '<label for="a-3">3</label>' +
      '</div>';
$("div.ui-content").append( $(bar) ).enhanceWithin();
$("input").eq(2).trigger("click").checkboxradio("refresh");

这将产生 2 个选择单选按钮。

【问题讨论】:

  • 您到底想做什么?动态选择单选按钮而不刷新单选组,对吧?
  • 不是选择,而是触发点击。在纯 HTML 中,C 上的 trigger("click") 取消选中无线电 A,而在 JQM 中则没有。见jsbin.com/ofuhaw/1202

标签: javascript jquery jquery-mobile radio-button checked


【解决方案1】:

我已经关注你的link 只是替换这个

$(document).on("click", "#btn2", function () {
    //$("#b-3").trigger("click").checkboxradio("refresh");
    $("[for=b-3]").trigger("click");
});

它对我有用

【讨论】:

  • 第一个仍然被选中。
  • @omar 我已经通过下载文件检查了这一点,但到目前为止“频繁”可能没有更新代码。
【解决方案2】:

TheMohanAhuja 给出了正确答案。 jQM增强复选框后,它响应的是对标签元素的点击而不是输入。

所以对于你在 OP 中给出的代码,只需更改最后一行即可触发对标签的点击:

$("div.ui-content").empty();
var bar = '<div data-role="controlgroup">' +
  '<input type="radio" name="a" id="a-1" value="choice-1" checked="checked">' + 
  '<label for="a-1">1</label>' +
  '<input type="radio" name="a" id="a-2" value="choice-2">' +
  '<label for="a-2">2</label>' +
  '<input type="radio" name="a" id="a-3" value="choice-3">' +
  '<label for="a-3">3</label>' +
  '</div>';
$("div.ui-content").append( $(bar) ).enhanceWithin();

$(".ui-radio label").eq(2).trigger("click");

这是一个DEMO

【讨论】:

  • 不错的技巧...我还在 JQM 上提交了一个错误,该错误已修复 pr
猜你喜欢
  • 1970-01-01
  • 2012-09-14
  • 1970-01-01
  • 2011-09-06
  • 2013-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多