Javascript Jquery 选择所有带有以字符串开头的innerHTML 的元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3631199/
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
Jquery select all elements with an innerHTML that starts with a string?
提问by DevDevDev
I know you can use :contains to get elements who's innerHTML contains a certain string, but how can I get the elements whose innerHTML starts with a string?
我知道你可以使用 :contains 来获取那些 innerHTML 包含某个字符串的元素,但是我怎样才能获取其 innerHTML 以字符串开头的元素呢?
回答by joshperry
Using a filter function you can filter based on any criteria that you'd like:
使用过滤器功能,您可以根据您喜欢的任何条件进行过滤:
var spans = $("span").filter(function(idx) {
return this.innerHTML.indexOf(myString) == 0;
});
回答by yincrash
I know this is old, but if anyone is looking for a better answer, jQuery since v1.1.4 has a ":contains("text")" selector.
我知道这是旧的,但如果有人正在寻找更好的答案,jQuery 自 v1.1.4 就有一个":contains("text")" 选择器。
Example HTML:
示例 HTML:
<p>Please reply above this line...</p>
Example jQuery selects above HTML:
示例 jQuery 选择上面的 HTML:
$('p:contains("Please reply above this line")');
回答by KeatsKelleher
You could do something like this:
你可以这样做:
<!doctype HTML>
<html>
<head>
<script type = "text/javascript" language = "JavaScript" src = "jquery-1.4.2.min.js"></script>
<script type = "text/javascript" language = "JavaScript">
var elems;
$(document).ready(function(){
$("div").each(function(){
var content = $(this).html();
if (content.match(/asdf/)){
alert(content);
}
});
});
</script>
</head>
<body>
<div>asdfaowhguiwehgiuh</div>
<div>asdfaowhguiwehgiuh</div>
<div>fdsaaowhguiwehgiuh</div>
<div>fdsaaowhguiwehgiuh</div>
<div>fdsaaowhguiwehgiuh</div>
<div>asdfaowhguiwehgiuh</div>
</body>
</html>
In order to find whether it's in the content at all..if you want the first few characters you should split the content on those characters and test just it.
为了找到它是否在内容中......如果你想要前几个字符,你应该将这些字符的内容分开并测试它。
回答by Justin Russell
The filter method will let you compare an element's content, and then you can do whatever you like (in this case, I've done addClass('selected')).
filter 方法可以让你比较一个元素的内容,然后你可以做任何你喜欢做的事情(在这种情况下,我已经做了addClass('selected'))。
$('p').filter(function() {
var searchString = 'Blue';
return ($(this).html().substring(0, searchString.length) == searchString);
}).addClass('selected');
Demo:
演示:

