在 .change() JavaScript 上保存之前的搜索

Save previous search on .change() JavaScript

我正在尝试使用 jquery 移动过滤器功能过滤单词,同时使用我在此处找到的一些代码突出显示用户正在搜索的单词。

$(document).ready(function(){
  jQuery.fn.highlight = function (str, className) {
    var regex = new RegExp(str, "gi");
    return this.each(function () {
      $(this).contents().filter(function() {
        return this.nodeType == 3 && regex.test(this.nodeValue);
      }).replaceWith(function() {
        return (this.nodeValue || "").replace(regex, function(match) {
            return "<span class=\""+" test " + className + "\">" + match + "</span>";
        });
      });
    });
  };
  $("#search-basic").change(function(){
    var search = $("input[name=search]").val();
    $(".test").replaceWith(search);
    // This commented part is the part where it creates a los of spans, tried to solve it with the code above but so far it does not work.
    // var unset = $(".test");
    // unset.removeClass("highlight");
    // var search = $("input[name=search]").val();
    $(".testHighlight *").highlight(search, "highlight");
  });


});

我的问题是,在多次搜索结束时,用户将无法看到他的搜索词突出显示,因为 JS 创建了太多 < spans > 函数突出显示将找不到这些词。

有没有办法保存先前在搜索字段中插入的值,然后用该词替换整个 ?我正在使用 .change() 函数来触发整个过程,但那样我就无法找到输入字段的先前值。

为什么不删除添加的 <span> 标签?

$("#search-basic").change(function(){
    var elementWithTextToHighlight = $("..."),
        domNode = elementWithTextToHighlight.get(0);

    $("span.highlight").contents().unwrap();  // get rid of the span tags
    domNode.normalize();  // combine all text nodes into one

    var search = $("input[name=search]").val();
    elementWithTextToHighlight.highlight(search, "highlight");
});

您还应该在突出显示脚本中添加空字符串检查。否则,它将为文本中的每个字符添加一个空的 span 标签。这也会破坏功能。

jQuery.fn.highlight = function(str, className) {
    if (str === "") {
        return this;
    }
    // the rest of the function...
}

fiddle

$(document).ready(function() {
  jQuery.fn.highlight = function(str, className) {
    if (str === "") {
        return this;
    }
    var regex = new RegExp(str, "gi");
    return this.each(function() {
      $(this).contents().filter(function() {
        return this.nodeType == 3 && regex.test(this.nodeValue);
      }).replaceWith(function() {
        return (this.nodeValue || "").replace(regex, function(match) {
          return "<span class=\"" + " test " + className + "\">" + match + "</span>";
        });
      });
    });
  };

  $("#search-basic").change(function () {
    var elementWithTextToHighlight  = $("p"),
        domNode  = elementWithTextToHighlight.get(0);
    $("span.highlight").contents().unwrap().get(0);
    domNode .normalize();
    
    var search = $(this).val();
    elementWithTextToHighlight.highlight(search, "highlight");
  });
});
.highlight {
  background-color: yellow
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
  sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
  Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>

<input id="search-basic" type="text" name="search" />