通过jQuery隐藏第二行表中的跨度

Hide span in second table row through jQuery

本文关键字:二行 隐藏 jQuery 通过      更新时间:2024-04-10

我有一个在烧瓶中生成的表:

<table class="table" id="preferencesTable">
  <thead>
    <th>
      <span>Fall 2016 Course Preferences</span>
      <span id="addPreference" class="glyphicon glyphicon-plus-sign pull-right"></span>
    </th>
  </thead>
  <tbody>
    {% for row in data.course_preferences %}
        <tr id="{{row.id}}">
          <td>
            {{ row.name }}
            <span class="pull-right">
              <span class="glyphicon glyphicon-arrow-up icon_padding"></span>
              <span class="glyphicon glyphicon-arrow-down icon_padding"></span>
              <span class="glyphicon glyphicon-remove icon_padding></span>
              <span class="glyphicon glyphicon-remove icon_padding></span>
            </span>
          </td>
        </tr>
    {% endfor %}
  </tbody>
</table>

我想让上下箭头移动表格行的顺序。因为第一个表行(不包括表头)在顶部,所以不需要向上箭头。我想把箭藏起来。

我能够找到以下跨度:

$('#preferencesTable tr:nth-child(2) span')[2]

返回

<span class=​"glyphicon glyphicon-arrow-down icon_padding">​::before​</span>​

但是我失去了显示和隐藏跨度的所有能力(.css、.hide等不再有效)。

如何仅在第一行隐藏此跨度

您需要访问表的tbody下的第一个子级,然后您可以找到具有类glyphicon-arrow-upspan并将其隐藏。此外,使用[2]访问span将返回一个dom元素引用,而不是jQuery对象,因此您将无法使用它调用任何jQuery方法。

tr:nth-child(2)将选择其父级的第二个子级tr,在这种情况下,它将选择tbody 中的第二个tr

$('#preferencesTable tbody tr:first-child span.glyphicon-arrow-up').hide()

Arun p Johny给出的答案似乎是正确的。

我还创建了一个jsfiddle:点击此处查看演示

您可以将此JS放入事件处理程序中,以便在某些操作中始终隐藏第一行的向上箭头。

$('selector').eventName(function(){
      $('#preferencesTable tbody tr:first-child span.glyphicon-arrow-up').hide();
});

我认为问题在于,当您使用方括号运算符时,您会得到一个普通的JavaScriptDOM对象。请参阅:https://learn.jquery.com/using-jquery-core/faq/how-do-i-pull-a-native-dom-element-from-a-jquery-object/

您可以通过在$()中包装该DOM对象来获得jQuery对象来解决此问题,如下所示:

var firstRowSpan = $('#preferencesTable tr:nth-child(2) span')[2];
firstRowSpan = $(firstRowSpan);
firstRowSpan.hide();

另请参阅:将DOM转换为jQuery