在 jQuery 中获取具有特定内部 HTML 值的所有链接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2241826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:05:27  来源:igfitidea点击:

Getting all links with specific inner HTML value in jQuery

jqueryjquery-selectors

提问by Fitzchak Yitzchaki

<div>
    <a>
       Text1
       <img alt="" stc="" />
    </a>
    <a>
       Text2
    </a>
 </div>

I want to select all anchor elements that have text=text2. I'm looking for something like this:

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

$('a[text=Text2]')
$('a[text=Text2]')


Edit:Why this is not working? For some some reason, it needs to be in this format:

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

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

回答by gnarf

You ask why this doesn't work:

你问为什么这不起作用:

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

The reason is, .find()will search children elements, you want .filter()(because you already selected the a- or you add the :containsto the a find:

原因是,.find()会搜索你想要的子元素.filter()(因为你已经选择了a- 或者你添加:contains了一个查找:

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

回答by Kevin Gorski

You're looking for contains:

您正在寻找包含

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

回答by Amy

As an additional note, rather than scanning for exact text inside a link it might be better to be scanning for attributes, e.g.

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

<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>

Now you can (accurately) scan for:

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

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

(I'm a big fan of the data-* attributes.)

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

回答by Chetan Sastry

Use the :contains()filter.

使用:contains()过滤器。

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

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