如果元素的内部文本与 jquery 中的模式匹配,如何获取元素? [英] How get an element if its inner text matches a pattern in jquery?
问题描述
考虑像下面这样的 html,
{{ 一些文本 }}<span class="测试">{{ asdknfsdf }}</span>
我想获取内部文本与 {{ <sometext> 匹配的所有元素}}
在 jquery 中.我尝试了以下代码,但无法正确获取元素.我在这里错过了什么?
var elements = [];$('*:contains("{{ .* }}")').each(function(){元素推(这个);});
几件事:
1) 无法正确获取元素"并不是非常具有描述性.你没有结果吗?出乎意料的结果?
2) 通过使用 *:contains
选择器,您要求包含指定文本的每个元素.这意味着您将html
、body
和其他父元素以及最近的div
.将选择器的范围限定为 div
元素,或者甚至更好,限定为您知道可能包含预期结果的类.
3) 您可以通过简单地对选择器的结果调用 makeArray()
来简化您的逻辑:
var elements = $.makeArray($('body *:contains("{{ sometext }}")'));console.log('元素::', 元素);
Consider a html like below,
<div id="test">
{{ sometext }}
</div>
<span class="testing">
{{ asdknfsdf }}
</span>
I want to get all the elements whose inner text matches {{ <sometext> }}
in jquery. I tried the below code, but I could not get the elements properly. What am I missing here?
var elements = [];
$('*:contains("{{ .* }}")').each(function(){
elements.push(this);
});
Several things:
1) "Could not get the elements properly" isn't terribly descriptive. Are you getting no results? Unexpected results?
2) By using a selector of *:contains
, you are asking for every element that contains the specified text. That means you'll html
, body
, and other parent elements as well as the nearest div
. Scope your selector to just div
elements, or even better, to a class that you know might contain the expected result.
3) You can simplify your logic by simply calling makeArray()
on the result of your selector:
var elements = $.makeArray($('body *:contains("{{ sometext }}")'));
console.log('elements ::', elements);
这篇关于如果元素的内部文本与 jquery 中的模式匹配,如何获取元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!