【问题标题】:swap radios if selected using jquery如果使用 jquery 选择,则交换收音机
【发布时间】:2013-03-05 12:58:14
【问题描述】:

单击 radiogroup2 中的单选按钮时,所选收音机应与 id='selectedradio' 的收音机交换位置。小提琴http://jsfiddle.net/DCC66/6/ --- 更新 --- 无线电行和代码的清晰视图正在交换但取消http://jsfiddle.net/DCC66/14/

尝试对 id 问题进行排序:http://jsfiddle.net/DCC66/18/

$(".radiogroup2 input[type='radio']").on('click', function () {
    $('#radioselected').closest('label').before($(this).closest('label'));
    $(this).closest('label').after($('#radioselected').closest('label'));
    $(this).attr('domaintype', 'radioselected');
    $('radioselected').attr('radioselected', 'domaintype');
});

现在 this:// 交换一次然后停止,然后只是使单击的收音机消失。认为它需要将 id="radioselected" 添加到新交换的收音机中。虽然只更换了收音机,但仍然没有交换。

$(".radiogroup2 input[type='radio']").on('click', function () 
{
    $('#radioselected').closest('label').replaceWith($(this).closest('label'));
});

尝试使用克隆仍然没有运气:

$("div.radiogroup2 input[name='domain_ext']").click(function () 
{
    $(this).clone('#radioselected').after(this);
});

原创

$("div.radiogroup2 input[name='domain_ext']").click(function() 
{ 
    //only if a the radio in radiogroup to are clicked take radio and swap with id='radioselected'
    if  ($(this).prop('checked')) 
    {
        $(this).after('#radioselected').add(this);
        $('#radioselected').after(this);
    }
});

因此,在“交换”行中单击的任何无线电都应与第一行中 ID 为“selectedradio”的无线电交换位置

【问题讨论】:

  • 你想只交换单选按钮,还是同时交换标签?
  • 标签也是如此,整个代码都是针对那个元素的,以防万一用户想要点击其他东西。

标签: javascript jquery jquery-ui jquery-plugins radio-button


【解决方案1】:

使用委托而不是直接在单选按钮上绑定事件。这样,被交换到 div 中的单选按钮也将起作用。

使用closest 方法获取单选按钮周围的标签。

从您交换的单选按钮中删除 id,并将其添加到选定的单选按钮。

使用after 方法将标签移动到所选单选按钮旁边的第二个列表中,然后使用prependTo 将带有所选单选按钮的标签移动到第一个列表中。

您有一些无效的 HTML 代码使行交换位置。将<td><tr> 更改为<tr><td>

$("div.radiogroup2").on("click", ":radio", function () {
  var l = $(this).closest('label');
  var r = $('#radioselected');
  r.removeAttr('id');
  l.after(r.closest('label'));
  $(this).attr('id', 'radioselected');
  l.prependTo('.radiogroup1');
});

演示:http://jsfiddle.net/DCC66/16/

【讨论】:

  • 哈哈,太优雅了,你们巫师旋转代码的方式,非常感谢。
猜你喜欢
  • 1970-01-01
  • 2012-11-13
  • 1970-01-01
  • 2017-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-22
  • 1970-01-01
相关资源
最近更新 更多