【问题标题】:How can I use jquery to toggle "checked" for radio buttons within clickable table cells?如何使用 jquery 在可点击的表格单元格中切换“选中”单选按钮?
【发布时间】:2012-07-19 20:20:25
【问题描述】:

我有几个在表格中嵌入了单选按钮和复选框的表单。我想要两个使用 jquery 做两件事:

  • 首先,用户可以通过单击包含按钮的表格单元格来“单击”单选按钮或复选框。

  • 其次,用户可以通过单击两次来切换复选框单选按钮。因此,单击已选中的单选按钮(或包含它的单元格)应该取消-选中它,不会在组内留下单选按钮。

我可以分别做这两个,但我坚持让它们一起工作。请帮忙!

这是我的不太正常的 jquery 代码:

$(".clickable", Q)
    .mouseover( function(){ $(this).addClass('mouseover-cell'); })
    .mouseout( function(){ $(this).removeClass('mouseover-cell'); })
    .click( function(event){
        if( event.target.type != 'checkbox' && event.target.type != 'radio' ){
            var x = $('input', this).attr("checked");
            $('input', this).attr("checked", !x);

            //$('input', this).trigger("click");
        }
        return false;
    });

单个按钮的 html 如下所示:

<tr>
  <td>
    Label for the button group
  </td>
  <td class="clickable">
    <input type="radio" name="q1" value="1">
  </td>
  <td class="clickable">
    <input type="radio" name="q1" value="2">
  </td>
  <td class="clickable">
    <input type="radio" name="q1" value="3">
  </td>
</tr>

【问题讨论】:

  • 尝试.prop()而不是.attr()进行检查
  • 谢谢!这更接近了,但并不完全在那里。在我尝试通过单击按钮本身(而不是表格单元格)来取消选择单选按钮的情况下,它会失败。 AFAICT,其他一切正常!

标签: jquery radio-button


【解决方案1】:

您的代码在布局略有不同的情况下运行良好。

你可以在这里测试一下

Clickable cells

$(".clickable").mouseover( function(){ $(this).addClass('mouseover-cell'); });
$(".clickable").mouseout( function(){ $(this).removeClass('mouseover-cell'); });
$(".clickable").click( function(event){
    if( event.target.type != 'checkbox' && event.target.type != 'radio' ){
        var x = $('input', this).attr("checked");
        $('input', this).attr("checked", !x);
    }
    return false;
});​

<table border="1">
<tr>
  <td>
    Label for the button group
  </td>
  <td class="clickable">
    <input type="radio" name="q1" value="1">
  </td>
  <td class="clickable">
    <input type="radio" name="q1" value="2">
  </td>
  <td class="clickable">
    <input type="radio" name="q1" value="3">
  </td>
</tr>
</table>​

【讨论】:

  • 不,这不能解决问题 - 尝试单击单选按钮本身。
  • 您使用的是哪个浏览器?你有 jQuery 吗?它可以在 chrome 上正常工作,无论是单击单元格还是单击单选按钮。你试过我发布的链接吗?
  • 我正在使用带有 jquery 的 Chrome v20,我确实尝试了该链接。问题是通过单击按钮本身取消选择单选按钮。
猜你喜欢
  • 2021-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-15
  • 2014-01-14
  • 2022-01-12
  • 1970-01-01
相关资源
最近更新 更多