单击td,在jQuery中选择单选按钮

Nic*_*ick 7 jquery button radio

一些非常基本的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>
Run Code Online (Sandbox Code Playgroud)

jQuery的:

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

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

 });
Run Code Online (Sandbox Code Playgroud)

非常感谢任何帮助,谢谢!

Sar*_*raz 13

使用此选择器:

$('input:radio', this).attr('checked', true);
Run Code Online (Sandbox Code Playgroud)

或使用find方法:

$(this).find('input:radio').attr('checked', true);
Run Code Online (Sandbox Code Playgroud)

以下是您的代码的外观:

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

  • 当用作上下文时,不需要在jQuery构造函数中包装`this`,`$('input:radio',this)`就足够了. (2认同)