【问题标题】:Getting all links with specific inner HTML value in jQuery在 jQuery 中获取具有特定内部 HTML 值的所有链接
【发布时间】:2017-03-03 03:08:21
【问题描述】:
<div>
    <a>
       Text1
       <img alt="" stc="" />
    </a>
    <a>
       Text2
    </a>
 </div>

我想选择所有具有text=text2 的锚元素。我正在寻找这样的东西:

$('a[text=Text2]')

编辑:为什么这不起作用?出于某种原因,它需要采用这种格式:

$('div').find('a').find(':contains("Text2")')

【问题讨论】:

    标签: jquery jquery-selectors


    【解决方案1】:

    你问为什么这不起作用:

    $('div').find('a').find(':contains("Text2")')
    

    原因是,.find() 将搜索子元素,您想要 .filter()(因为您已经选择了 a - 或者您将 :contains 添加到查找中:

    $('div').find('a').filter(':contains("Text2")');
    $('div').find('a:contains("Text2")');
    

    【讨论】:

    • 忘记了.filter()。谢谢。
    • 我想知道您为什么不将初始选择器更改为 $('div a:contains("Text2")') 而不是 Find/Filter 链? jQuery 选择器像 CSS 选择器一样遍历后代。
    • @kevin 因为操作中的评论:'由于某些原因,它需要采用这种格式'
    • 还有@Kevin Gorski - 如果您使用.find().filter() 方法,选择器的速度实际上要快得多。找到a可以使用getElementsByTagNamequerySelectorAll进行优化。但是,CSS3 (QSA) 不支持 jQuery :contains() 选择器,因此强制使用 sizzle 解析选择器,而不是首先使用更快的浏览器选择。 jsperf.com/quick-selector-test 进行性能测试
    【解决方案2】:

    你正在寻找contains:

    $("a:contains('text2')")
    

    【讨论】:

      【解决方案3】:

      使用:contains() 过滤器。

      http://api.jquery.com/contains-selector/

      【讨论】:

        【解决方案4】:

        作为附加说明,与其扫描链接中的确切文本,不如扫描属性,例如

        <div class="farm-market-items">
          <a class="market-item" data-item-type="seed" data-item-id="817">
            Carrot Seed
            <img alt="" src="" class="item-thumb" />
          </a>
          <a class="market-item" data-item-type="seed" data-item-id="25">
            Spinach Seed
          </a>
          <a class="market-item" data-item-type="tree" data-item-id="981">
            Pear Tree
          </a>
        </div>
        

        现在您可以(准确)扫描:

        all_seeds = $('a[data-item-type="seed"]');
        

        (我是 data-* 属性的忠实粉丝。)

        【讨论】:

        • 出于某种原因,它需要采用上述格式。所以我必须只从 innerText 查询它。
        猜你喜欢
        • 1970-01-01
        • 2016-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-16
        • 1970-01-01
        相关资源
        最近更新 更多