【问题标题】:Jquery select tbody but not from nested tablesJquery 选择 tbody 但不是从嵌套表中选择
【发布时间】:2014-09-24 12:30:51
【问题描述】:

我正在尝试将数据附加到使用 jquery 选择的表中。问题是,该表中可能有嵌套表。发生的情况是,当我附加数据时,不仅父表的 tbody 被附加,所有子表的 tbody 也被附加。这是我的代码:

var template = window.app.getTemplate('myTemplate');
var image = {id: imageId, name: imageName, imageList: imageTypes, extension: ext, thumbNail: thumbNailPath};
$("#MyTable tbody:first").append(template(image));

myTemplate 的设置如下:

<tr>
   <td>
      <table>
        <tr>
          <td></td>
        </tr>
        <tr>
           <td></td>
        </tr>
     </table>
   </td>
<tr>
</tr>
   <td></td>
</tr>

MyTable 是这样设置的:

<table id="MyTable" data-attr="images">
    <thead>
    </thead>
    <tbody>       
    </tbody>
</table>

就像我说的,当追加发生时,如果 tbody 中有多个表,则所有 tbody 都会被追加。那么,如何只选择第一个呢?

谢谢

【问题讨论】:

  • 你可以使用'>'操作符来查找tbody为$("#MyTable &gt; tbody")
  • tbody:first 应该防止在所有 tbody 上附加...你能重现这个问题吗?我不能..

标签: javascript jquery backbone.js


【解决方案1】:

JQuery 使用 CSS 选择器到达元素。

$("#MyTable > tbody:first")

E > F 匹配作为元素 E 的子元素的任何 F 元素。

在http://www.w3.org/TR/CSS2/selector.html#child-selectors查看更多信息

【讨论】:

    【解决方案2】:

    也许如果你更新你的 jquery 选择器

    $("#MyTable > tbody:first")
    

    【讨论】:

      【解决方案3】:

      试试:

      $("#MyTable > tbody").append(template(image));
      

      【讨论】:

        猜你喜欢
        • 2011-03-06
        • 2017-02-01
        • 2016-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多