0

我在 HTML 中的一个例子:

<table id="testME">
   <tr>
      <td><input id="first" name="choices" type="radio" value="1"></td>
      <td><input id="second" name="choices" type="radio" value="2"></td>
      <td><input id="third" name="choices" type="radio" value="3"></td>
   </tr>
   <tr>
      <td><label for="first">My first selection</label></td>
      <td><label for="second">My second selection</label></td>
      <td><label for="third">My third selection</label></td>
   </tr>
   <tr>
      <td><input id="myWords" type="text" /></td>
      <td><select id="mySelects">
             <option value="30">Choice 1</option>
             <option value="31">Choice 2</option>
          </select>
      </td>
      <td><input id="multiOne" name="multiSelect" type="checkbox" value="one" />
          <label for="multiOne">One</label><br />
          <input id="multiTwo" name="multiSelect" type="checkbox" value="two" />
          <label for="multiTwo">Two</label><br />
          <input id="multiThree" name="multiSelect" type="checkbox" value="three" />
          <label for="multiThree">Three</label><br />
          <input id="multiFour" name="multiSelect" type="checkbox" value="four" />
          <label for="multiFour">Four</label><br />
      </td>
   </tr>
</table>

我想要发生的是,当我单击单选按钮或其标签时,该列中的所有单元格(无论是 th 还是 td)都会以某种颜色突出显示。我想用 JQuery 来做这件事。

在发布这个问题之前我正在研究的内容:

<script>
function highlightSelection() {
        $('#testME > tr > td:nth-child(2)').css('background-color', 'gray');
    }
</script>
<input id="jquerytest" type="button" onclick="javascript:highlightSelection();" value="Change Color" />@:&nbsp; &nbsp; &nbsp;

但这似乎不起作用。

4

1 回答 1

2

像这样的东西:

$("table").on("click", "input", function() {
    var td = $(this).parent("td"),
        tdIndex = td.index();
    var tr = td.parent("tr"),
        trIndex = tr.index();

    $("table, table tr, table tr td").css("background", "none");

    $("td:eq(" + tdIndex + ")", "tr").css("background", "red");
    $("tr:eq(" + trIndex + ")").css("background", "blue");

});​

小提琴:http: //jsfiddle.net/maniator/rZqdP/

于 2012-09-04T16:33:47.227 回答