jQuery基于文本选择 [英] jQuery select based on text

查看:90
本文介绍了jQuery基于文本选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据jQuery中的文本选择一个元素.

I need to select an element based on its text in jQuery.

例如:

<span>this text</span>

我知道我可以使用.contains()基于文本进行选择,但这不是排他性的.

I know I can use .contains() to select based on text, but it's not exclusive.

我不想选择:

<span>this text and that text</span>

如果元素是唯一的文本,我想选择该元素.

I want to select the element if it's the only text of the element.

除了使用正则表达式外,如何使用jQuery选择器做到这一点?

Aside from using regex, how do I do this with jQuery selectors?

谢谢.

推荐答案

使用:contains选择器可以发挥一定的作用,但是到目前为止.您将需要根据精确的文本匹配进一步缩小元素集,如:

You have some leverage with the :contains selector, but that only goes so far. You will need to further trim down the set of elements based on exact text matches, as in:

$("span:contains(this text)")
.filter
(
  function()
  {
    return $(this).text() === "this text";
  }
)

从技术上讲,这样就不需要使用首字母大写了,但是在筛选成所需的确切集合之前,可以从较小的SPAN元素集合开始,从而获得性能上的好处.

This makes the initial contains usage technically unnecessary, but you may experience performance benefits by starting out with a smaller collection of SPAN elements before filtering down to the exact set you're interested in.

编辑:肯·布朗宁(Ken Browning)建议在filter函数中使用text()函数而不是innerHTML进行字符串比较.这样的想法是innerHTML将捕获我们不特别感兴趣的文本(包括标记).

EDIT: Took Ken Browning's suggestion to use the text() function instead of innerHTML for string comparison within the filter function. The idea being that innerHTML will capture text that we're not particularly interested in (including markup).

这篇关于jQuery基于文本选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆