【问题标题】:jquery :first element of a list of anchor tagsjquery:锚标签列表的第一个元素
【发布时间】:2011-09-07 10:19:30
【问题描述】:

我的 jquery 是这样的

$('#content a[href*="Something"]')

并返回这个

[<a href="Something1">blah</a>,
 <a href="Something2">blah</a>,
 <a href="Something3">blah</a>,
 <a href="Something4">blah</a>]

我正在尝试使用:first 来获取第一个元素。

$('#content a[href*="Something"]:first')

但它不起作用。 #content 部分似乎引起了问题。如何在不删除 #content 的情况下解决此问题?

编辑:我的html

<div id="content>
  <a href="Something1">blah</a>
  <a href="Something2">blah</a>
  <a href="Something3">blah</a>
  <a href="Something4">blah</a>
</div>

【问题讨论】:

  • 能否提供完整或详细的 HTML 代码?

标签: jquery


【解决方案1】:

【讨论】:

    【解决方案2】:

    我不确定为什么 :first 不适合你,它在类似情况下也适合我,但如果没有其他方法,请尝试改用 filter()

    $('#content a[href*="Something"]').filter(':first')
    

    【讨论】:

      【解决方案3】:

      使用eq selector

      $('a[href*="Something"]:eq(0)')
      

      如果你想使用上下文,那么试试这个。

      var context = $('#content');
      var firstElement = $('a[href*="Something"]:eq(0)',context);
      

      【讨论】:

      • 元素的索引为 0,所以这应该是 $('a[href*="Something"]:eq(0)')
      • @shortstick:已更正,但目的是使用正确的选择器。
      • :first 与 :eq(0): stackoverflow.com/questions/1234087/… 一样有效
      • @shortstick:我检查了 :first 它不起作用,因此得到了答案。
      猜你喜欢
      • 2021-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-29
      • 2016-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多