在 div 类中使用 javascript 搜索文本 [英] Search for text with javascript inside a div class

查看:39
本文介绍了在 div 类中使用 javascript 搜索文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个脚本,我可以在其中自动搜索某个字符串(没有文本框或任何东西,我想按下一个按钮,它会在 a 中搜索单词bear",例如使用document".getElementByClassName"...我的 C# 开发人员的大脑开始寻找内容"或包含"之类的东西,但我失败了...谁能帮我提供示例代码?

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?

提前致谢:)

推荐答案

我建议使用 jquery 来轻松地通过类名获取元素并识别具有搜索值的元素.类似的东西:

I'd suggest using jquery to easily get the elements by class name and identify those with the search value. Something like:

var searchValue = "bear";

$(".ClassName").each(function(){
  if($(this).html().indexOf(searchValue) > -1){
     //match has been made
  }
});

如果您仅限于使用 vanilla javascript,这里是一个示例:

if you are restricted to vanilla javascript, here is an example:

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   
  }
}

我认为您真正要寻找的是比较器 String.indexOf(SearchValue) >-1,它将识别元素的内容是否与您要查找的字符串匹配.请注意,它区分大小写.

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.

这篇关于在 div 类中使用 javascript 搜索文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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