javascript - 如何在 JavaScript 中突出显示搜索结果中匹配的子字符串

标签 javascript html css

我是 JavaScript 的新手。尝试构建一个小型用户界面,当我们向搜索框发出查询时搜索单词列表。有了这个,我想在列表框中突出显示每个单词的匹配子字符串,以便用户可以一眼看出单词与查询的匹配程度。为了实现这个目标,我引用了一些基本的 JS 教程,在我的代码中包含了 highlight 功能。但是由于某些错误,它无法正常工作。你能帮我么。谢谢..!!!

    function getFullName(item,index) { 
        return "<li>"+item.firstname + "<span class='tool-tip'>" +item.lastname+"</span> "+ item.id+"</li>";
    }
    function myFunction1() {
        document.getElementById("demo").innerHTML = persons.map(getFullName);
    }

    function myFunction() {
        var input, filter, ul, li, a, i,count=0;
        input = document.getElementById("myInput");
        filter = input.value.toUpperCase();

      var longWords = persons.filter(function(person){

         return  person.firstname.toUpperCase().indexOf(filter) > -1 
    });
        var message = "Result:" + longWords.length + " words containing '" + input.value;
        document.getElementById("demo").innerHTML=message;

        ul = document.getElementById("myUL");
        ul.innerHTML= longWords.map(getFullName);
        highlight();
    }
    function highlight(){
        var inputText, filter1,innerHTML,index;
        inputText = document.getElementById("myInput");
        console.log(inputText);
        filter1 = inputText.value.toUpperCase();
        console.log(filter1);
        innerHTML1 = inputText.innerHTML;
        console.log(innerHTML1);
        index1 = innerHTML1.indexOf(filter1);
    if ( index1 >= 0 )
    { 
        innerHTML1 = innerHTML1.substring(0,index1) + "<span class='highlight'>" + innerHTML1.substring(index1,index1+filter1.length) + "</span>" + innerHTML1.substring(index1 + filter1.length);
        filter1.innerHTML = innerHTML1; 
    }

}

这是 CSS 文件:

.highlight{
             font-weight:bold;
             color:black;
 }

最佳答案

以下是我为突出显示添加书签的代码。在文本框中输入文本,您可以看到黄色高亮显示的文本

function highlight_text_nodes($nodes, word) {
  if (!$nodes.length) {
    return;
  }

  var text = '';

  // Concatenate the consecutive nodes to get the actual text
  for (var i = 0; i < $nodes.length; i++) {
    text += $nodes[i].textContent;
  }

  var $fragment = document.createDocumentFragment();

  while (true) {
    // Tweak this if you want to change the highlighting behavior
    var index = text.toLowerCase().indexOf(word.toLowerCase());

    if (index === -1) {
      break;
    }

    // Split the text into [before, match, after]
    var before = text.slice(0, index);
    var match = text.slice(index, index + word.length);
    text = text.slice(index + word.length);

    // Create the <mark>
    var $mark = document.createElement('mark');
    $mark.className = 'found';
    $mark.appendChild(document.createTextNode(match));

    // Append it to the fragment
    $fragment.appendChild(document.createTextNode(before));
    $fragment.appendChild($mark);
  }

  // If we have leftover text, just append it to the end
  if (text.length) {
    $fragment.appendChild(document.createTextNode(text));
  }

  // Replace the nodes with the fragment
  $nodes[0].parentNode.insertBefore($fragment, $nodes[0]);

  for (var i = 0; i < $nodes.length; i++) {
    var $node = $nodes[$nodes.length - i - 1];
    $node.parentNode.removeChild($node);
  }
}


/*
 * Highlights all instances of `word` in `$node` and its children
 */
function highlight($node, word) {
  var $children = $node.childNodes;
  var $current_run = [];

  for (var i = 0; i < $children.length; i++) {
    var $child = $children[i];

    if ($child.nodeType === Node.TEXT_NODE) {
      // Keep track of consecutive text nodes
      $current_run.push($child);
    } else {
      // If we hit a regular element, highlight what we have and start over
      highlight_text_nodes($current_run, word);
      $current_run = [];

      // Ignore text inside of our <mark>s
      if ($child.nodeType === Node.ELEMENT_NODE && $child.className !== 'found') {
        highlight($child, word);
      }
    }
  }

  // Just in case we have only text nodes as children
  if ($current_run.length) {
    highlight_text_nodes($current_run, word);
  }
}

/*
 * Removes all highlighted <mark>s from the given node
 */
function unhighlight($node) {
  var $marks = [].slice.call($node.querySelectorAll('mark.found'));

  for (var i = 0; i < $marks.length; i++) {
    var $mark = $marks[i];

    // Replace each <mark> with just a text node of its contents
    $mark.parentNode.replaceChild(document.createTextNode($mark.childNodes[0].textContent), $mark);
  }
}



var $p = document.querySelector('p');

document.querySelector('input').onkeyup = function() {
  unhighlight($p);

  if (this.value.length) {
    highlight($p, this.value);
  }
};
<input type="text" />

<p>
<b>JavaScript</b> is a high-level, dynamic, multi-paradigm, object-oriented, prototype-based, weakly-typed language traditionally used for client-side scripting in web browsers. JavaScript can also be run outside of the browser with the use of a framework like Node.js, Nashorn, Wakanda, or Google Apps Script. Despite the name, it is unrelated to the Java programming language and shares only superficial similarities.

Unless a tag for a framework or library is also included, a pure JavaScript answer is expected for questions with the javascript tag.
</p>

Edit, based on comment. Here is the jsfiddle version for OP.

jsfiddle 版本只是 tweek OP 的代码,让她了解它是如何工作的

关于javascript - 如何在 JavaScript 中突出显示搜索结果中匹配的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47132357/

相关文章:

javascript - 使用 window.open() AND ' 的多个窗口

javascript - 添加、删除、更新数据库记录后的最佳实践

javascript - 未捕获的 NotFoundError : Failed to execute 'insertBefore' on 'Node' : The node before which the new node is to be inserted is not a child of this node

javascript - 如何用 X 射线获取数组的第二项

javascript - 将 topLeft、topRight、bottomLeft 和 bottomRight id 的内容居中

javascript - 尝试让 jQuery 在单击时更改不同的 img src

html - 目标 safari css,但不是 chrome

javascript - jwPlayer onComplete 事件未触发(跨域嵌入)

javascript - Bootstrap Navbar 颜色在按下时不改变

html - 并排放置div,但不排成一行