在 div 类中使用 javascript 搜索文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21860663/
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
Search for text with javascript inside a div class
提问by user3324529
I want to make a script in which I can search for a certain string automatically (no text box or anything, I want to press on a button and it searches for the word "bear" for example inside a) using "document.getElementByClassName"...my C# dev brain started to go for something like "content" or "contains" but I failed terribly...can anyone help me with an example code?
我想制作一个脚本,在其中我可以使用“document.getElementByClassName”自动搜索某个字符串(没有文本框或任何东西,我想按下一个按钮并在 a 中搜索单词“bear”例如) ...我的 C# 开发人员的大脑开始寻找诸如“内容”或“包含”之类的东西,但我失败了...谁能帮我提供示例代码?
Thanks in advance :)
提前致谢 :)
回答by Will P.
I'd suggest using jquery to easily get the elements by class name and identify those with the search value. Something like:
我建议使用 jquery 通过类名轻松获取元素并识别具有搜索值的元素。就像是:
var searchValue = "bear";
$(".ClassName").each(function(){
if($(this).html().indexOf(searchValue) > -1){
//match has been made
}
});
if you are restricted to vanilla javascript, here is an example:
如果您仅限于使用 vanilla javascript,这里是一个示例:
var els = document.getElementsByClassName("ClassName");
var searchValue = "bear";
for(var i = 0; i < els.length; i++){
if(els[i].innerHTML.indexOf(searchValue) > -1){
//match has been made
}
}
I think what you are really looking for is the comparitor String.indexOf(SearchValue) > -1
, which will identify if the content of the element is a match for the string you are looking for. Note that it is case-sensitive.
我认为您真正要寻找的是 comparitor String.indexOf(SearchValue) > -1
,它将确定元素的内容是否与您要查找的字符串匹配。请注意,它区分大小写。
回答by Bic
You're looking for String.indexOf(string)
. JavaScript indexOf.
您正在寻找String.indexOf(string)
. JavaScript indexOf。
You can do something like this:
你可以这样做:
var elements = document.getElementsByClassName('class'); // get the elements
// loop through the elements
for (var i = 0; i < elements.length; i++) {
if (elements[i].innerHTML.indexOf(search) > -1) {
alert('found'); // popup
}
}