通过jquery选择元素伟大的孩子并改变它的宽度

时间:2017-01-31 11:10:46

标签: javascript

我需要在路径为<th>A</th>的表格中选择一个元素*[@id="something"]/table/thead/tr/th[2]并更改其宽度。

(function ITPscript() {
  $(document).ready(function() {
    $("#something table thead tr:nth-child(2)").width(1000);
  });
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="something" class="aaa">
  <table class="sortable">
    <thead>
      <tr>
        <th>0</th>
        <th>A</th>
        <th>B</th>
        <th>C</th>
        <th>D</th>
        <th>E</th>
        <th>F</th>
        <th>G</th>
        <th>H</th>
        <th>I</th>
        <th>J</th>
        <th>K</th>
        <th>L</th>
        <th>M</th>
        <th>N</th>
        <th>O</th>
      </tr>
    </thead>
    <tbody id="aBody">
      <tr>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
      </tr>
    </tbody>
    <tfoot></tfoot>
  </table>
</div>

我正在使用$("#something table thead tr:nth-child(2)").width(140);,但它不起作用。需要一种正确的方法来选择元素。

1 个答案:

答案 0 :(得分:0)

:nth-child未选择元素的第n个孩子,它会选择 的元素,即其父元素的第n个子元素。选择器必须是... tr th:nth-child(2)

(function ITPscript() {
  $(document).ready(function() {
    $("#something table thead tr th:nth-child(2)").width(1000);
  });
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="something" class="aaa">
  <table class="sortable">
    <thead>
      <tr>
        <th>0</th>
        <th>A</th>
        <th>B</th>
        <th>C</th>
        <th>D</th>
        <th>E</th>
        <th>F</th>
        <th>G</th>
        <th>H</th>
        <th>I</th>
        <th>J</th>
        <th>K</th>
        <th>L</th>
        <th>M</th>
        <th>N</th>
        <th>O</th>
      </tr>
    </thead>
    <tbody id="aBody">
      <tr>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
      </tr>
    </tbody>
    <tfoot></tfoot>
  </table>
</div>