【问题标题】:Click td, select radio button in jQuery单击 td,在 jQuery 中选择单选按钮
【发布时间】:2011-06-05 05:34:57
【问题描述】:

在使用一些非常基本的 jQuery 时遇到了一个小问题,我希望能够单击表格单元格,然后让它自动选择里面的单选按钮。

HTML:

  <table>
   <tr>
    <td>
     1<br>
     <input type="radio" name="choice" value="1">
    </td>
    <td>
     2<br>
     <input type="radio" name="choice" value="2">
    </td>
    <td>
     3<br>
     <input type="radio" name="choice" value="3">
    </td>
   </tr>
  </table>

jQuery:

 $("td").click(function () {

  $(this).closest('input:radio').attr('checked',true);

 });

任何帮助将不胜感激,谢谢!

【问题讨论】:

  • 由于答案已经正确,我将在这里添加 .closest() 用于遍历 up DOM 树,例如获取&lt;tr&gt;&lt;table&gt;,而不是向下。

标签: jquery button radio


【解决方案1】:

使用这个选择器:

$('input:radio', this).attr('checked', true);

或者使用find方法:

$(this).find('input:radio').attr('checked', true);

你的代码应该是这样的:

$("td").click(function () {
   $(this).find('input:radio').attr('checked', true);
});

【讨论】:

  • 在jQuery构造函数中使用this作为上下文不需要包裹,$('input:radio', this)就足够了。
  • 非常感谢!一件快速的事情是,我在选择单选按钮时更改了类,但是当您单击单元格时这不起作用,即使选择了单选按钮? $("td input[type=radio]").bind('change click', function () { $('td').removeClass('selected'); $(this).parent('td'). addClass('selected'); });
  • @Box9:已更新以避免进一步混淆:)
  • @Nick:你应该把它作为另一个问题发布:)
【解决方案2】:

试试

$(this).find('input:radio').attr('checked','checked');

【讨论】:

    【解决方案3】:

    尝试查找而不是最近的。

    $(this).find('input:radio').attr('checked',true);
    

    【讨论】:

      【解决方案4】:

      这很好用

       $(function () {
              $('td').click(function () {
      
              var cell = $(this),
                  state = cell.data('state') || 'first';
      
              switch (state) {
                  case 'first':
                      cell.data('state', 'second');
                      cell.find('input:radio').attr('checked', true);
                      cell.find('input:radio').data('checked', true);
                      cell.find('input:radio').prop('checked', true);
                      break;
                  case 'second':
                      cell.data('state', 'first');
                      cell.find('input:radio').attr('checked', false);
                      cell.find('input:radio').data('checked', false);
                      cell.find('input:radio').prop('checked', false);
                      break;
                  default:
      
                      break;
              }
          });
      });
      

      【讨论】:

        猜你喜欢
        • 2013-03-18
        • 1970-01-01
        • 2015-05-26
        • 2023-03-05
        • 1970-01-01
        • 2011-08-31
        • 1970-01-01
        • 1970-01-01
        • 2014-08-30
        相关资源
        最近更新 更多