Jquery选择tbody但不从嵌套表中选择

时间:2014-09-24 12:30:52

标签: javascript jquery backbone.js

我正在尝试将数据附加到表中,使用jquery进行选择。问题是,这个表中可能有嵌套表。会发生的事情是,当我追加数据时,不仅仅是父表的附加内容,而且所有子表也都附加了。这是我的代码:

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都会附加到。那么,我该如何只选择第一个?

感谢

3 个答案:

答案 0 :(得分:2)

JQuery使用CSS选择器来访问元素。

$("#MyTable > tbody:first")
  

E&gt; F匹配作为元素E的子元素的任何F元素。

http://www.w3.org/TR/CSS2/selector.html#child-selectors

了解详情

答案 1 :(得分:2)

也许你更新你的jquery选择器

$("#MyTable > tbody:first")

答案 2 :(得分:1)

尝试:

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