jquery:检查元素中是否存在字符串,返回布尔值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4553199/
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: check if string exist in element, return boolean
提问by evilReiko
Assuming I have this:
假设我有这个:
<div id="elementId">bla bla bla some text bla bla</div>
<div id="elementId">bla bla bla some text bla bla</div>
I want to check if this div text contains 'some text', then return true, otherwise return false, how to do that?
我想检查这个 div 文本是否包含“一些文本”,然后返回 true,否则返回 false,怎么做?
回答by Darin Dimitrov
var isContains = $('#elementId').text().indexOf('some text') > -1;
回答by Nick Craver
You can use the :contains()
selector and check the .length
to see if it matched anything, like this:
您可以使用:contains()
选择器并检查.length
它是否匹配任何内容,如下所示:
return $("#elementId:contains('some text')").length > 0;
回答by Felipe Campanhol
I used the same way of the buddy above...:
我用了和上面那个哥们一样的方法...:
if($('#div_searched').text().indexOf('bla') != -1)
if($('#div_searched').text().indexOf('bla') != -1)
This will return true when it found the word bla on div_searched
当它在 div_searched 上找到单词 bla 时,这将返回 true
回答by user3094826
I think this should also work.
我认为这也应该有效。
return $("#elementId:contains('some text')").length ? true : false;
It should return true if length greater than 0, otherwise it will return false.
如果长度大于 0,则返回 true,否则返回 false。