如何使用下面的代码突出显示搜索?

时间:2019-07-04 13:51:07

标签: javascript jquery find html-lists

下面的代码已经在li之间进行了字母搜索。我想重点介绍一下li中的字母。可以使用下面的代码吗?

<input type="search" id="catInput">
<ul id="myUl">
<li>Hello</li>
<li>Test</li>
<li>Javascript</li>
</ul>
<span id="total"></span>

<script>
var ip = document.getElementById('catInput');
var ul = document.getElementById('myUl');
var li = ul.getElementsByTagName('li');

document.getElementById('total').innerHTML = "" + (li.length) + "";
ip.addEventListener('input', function() {
  var val = this.value.toUpperCase(), idx = 0;
  for (var i = 0; i < li.length; i++) {
    var txt = li[i].textContent.toUpperCase();
    if (txt.indexOf(val) != -1) {
      li[i].style.display = '';
      idx++;
    } else {
      li[i].style.display = 'none';
    }
    if (idx == 0) {
        document.getElementById('total').innerHTML = "No results";
    }else{
        document.getElementById('total').innerHTML = idx;
    }
  }
});
</script>

1 个答案:

答案 0 :(得分:0)

if (textIndex != -1) {}条件内添加此代码,它将mark标签添加到匹配的输入中:

const rgxVal = `(${val})`;
const rgx = new RegExp(rgxVal, 'gi');
li[i].innerHTML = txt.replace(rgx, `<mark>$1</mark>`);

我还从toUpperCase()txt中删除了val,仅在测试匹配时添加了它:

const textIndex = txt.toUpperCase().indexOf(val.toUpperCase());
if (textIndex != -1) {
  ...

演示:

var ip = document.getElementById('catInput');
var ul = document.getElementById('myUl');
var li = ul.getElementsByTagName('li');

document.getElementById('total').innerHTML = "" + (li.length) + "";
ip.addEventListener('input', function() {
  var val = this.value, idx = 0;
  for (var i = 0; i < li.length; i++) {
    var txt = li[i].textContent;
    
    if(val) {
      var textIndex = txt.toUpperCase().indexOf(val.toUpperCase());
      if (textIndex != -1) {
        li[i].style.display = '';
        const rgxVal = `(${val})`;
        const rgx = new RegExp(rgxVal, 'gi');
        li[i].innerHTML = txt.replace(rgx, `<mark>$1</mark>`);
        idx++;
      } else {
        li[i].style.display = 'none';
      }
    } else {
      idx = 3;
      li[i].style.display = '';
      li[i].innerHTML = txt;
    }
  }
  if (idx == 0) {
     document.getElementById('total').innerHTML = "No results";
  } else{
     document.getElementById('total').innerHTML = idx;
  }
});
<input type="search" id="catInput">
<ul id="myUl">
<li>Hello</li>
<li>Test</li>
<li>Javascript</li>
</ul>
<span id="total"></span>