Javascript搜索子字符串

Javascript search for substring

本文关键字:字符串 搜索 Javascript      更新时间:2023-09-26

抱歉,因为这是一个我不能再访问或评论的帖子。

我试图写一个javascript函数,将搜索所有指定div在一个html页面的子字符串包含在我的搜索栏。我怎样才能简单地做到这一点?

这是我的代码到目前为止,我有它的工作,使showMe方法将只显示所选的div,我只需要子字符串代码现在工作。有人能帮帮我吗?

   <html>
<head>
<script type="text/javascript"> 
function dynamicSearch() {
    var val = document.getElementById('search').value;
    if (val == '')
      val = '-1';
    var srch = new RegExp(val, "gi");
    var els = document.getElementsByClassName('row');
    for (var idx in els) {
      if (idx != parseInt(idx))
        continue;
      var el = els[idx];
      if (typeof(el.innerHTML) !== 'undefined') {
        console.log(el.innerHTML);
        if (srch.test(el.innerHTML)) {
          el.style.display = 'block';
        } else {
          el.style.display = 'none';
        }
      }
    }
  }
function showMe (it, box) { 
var vis = (box.checked) ? "block" : "none"; 
document.getElementById(it).style.display = vis;
} 
</script>
</head>
<body>
<form>
<label for="search">Search:</label>
            <input type="text" name="search" id="search" onkeyup="dynamicSearch()"/>
<input type="checkbox" name="modtype" value="value1" onclick="showMe('div1', this)" />value1
<input type="checkbox" name="modtype" value="value2" onclick="showMe('div2', this)" />value2
<input type="checkbox" name="modtype" value="value3" onclick="showMe('div3', this)" />value3
<input type="checkbox" name="modtype" value="value4" onclick="showMe('div4', this)" />value4
<input type="checkbox" name="modtype" value="value5" onclick="showMe('div5', this)" />value5
<div class="row" id="div1" style="display:none">Show Div 1</div>
<div class="row" id="div2" style="display:none">Show Div 2</div>
<div class="row" id="div3" style="display:none">Show Div 3</div>
<div class="row" id="div4" style="display:none">Show Div 4</div>
<div class="row" id="div5" style="display:none">Show Div 5</div>
</form>
</body>
</html>

我在这里的代码正确运行为我的复选框,但我不能让它只显示搜索子字符串作为结果(即DynamicSearch函数不起作用,但showMe一个…或者至少我不能让DynamicSearch代码工作?)

简单的循环有什么问题?

function doSearch() {
 var val = $('searchBox').value;
 var els = document.getElementsByClassName('theDivs')
 //OR SIMILAR, whatever you need
 //var els = document.getElementsByTagName('div')
 for (el in els) {
  if (el.innerHTML.indexOf(val) >= 0)
   el.style.display = 'block'
  else
   el.style.display = 'none'
 }
}

编辑:看这个小提琴-基于你的其他小提琴:http://jsfiddle.net/nLxc4/5/