【问题标题】:Search function does not reset with input value of null搜索功能不会在输入值为 null 时重置
【发布时间】:2018-08-14 12:14:30
【问题描述】:

我有一个搜索和突出显示功能,它为内容 div 上的输入值字符串添加内联样式。

问题是当输入为空时,内联样式仍然存在于内容中。

我该如何防止这种情况或编写解决方法?提前谢谢你。

/**
 * highlight 1.0.0
 * Licensed under MIT
 *
 * Copyright (c) 2016 yjteam
 * http://yjteam.co.kr
 *
 * GitHub Repositories
 * https://github.com/yjseo29/highlight.js
 */

if (typeof jQuery === "undefined") {
  throw new Error("JavaScript requires jQuery");
}

+(function($) {
  "use strict";
  var version = $.fn.jquery.split(" ")[0].split(".");
  if (
    (version[0] < 2 && version[1] < 9) ||
    (version[0] == 1 && version[1] == 9 && version[2] < 1)
  ) {
    throw new Error("JavaScript requires jQuery version 1.9.1 or higher");
  }
})(jQuery);

+(function($) {
  $.fn.highlight = function(word, options) {
    var option = $.extend(
      {
        background: "#ffff00",
        color: "#000",
        bold: false,
        class: "",
        ignoreCase: true,
        wholeWord: true
      },
      options
    );
    var findCnt = 0;

    if (this.length == 0) {
      throw new Error("Node was not found");
    }

    var $el = $('<span style="color:' + option.color + ';"></span>');
    if (option.bold) {
      $el.css("font-weight", "bold");
    }
    if (option.background != "") {
      $el.css("background", option.background);
    }
    if (option.class != "") {
      $el.addClass(option.class);
    }

    if (option.wholeWord) {
      word = "\\b" + escapeRegExp(word) + "\\b";
    }
    var re = new RegExp(word, option.ignoreCase == true ? "gi" : "g");

    this.each(function() {
      var content = $(this).html();

      $(this).html(
        content.replace(re, function(t) {
          findCnt++;
          $el.text(t);
          return $el.get(0).outerHTML;
        })
      );
    });
    return findCnt;

    function escapeRegExp(string) {
      return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
    }
  };
})(jQuery);



// highlight search terms in content
var searchCnt = 0;

var option = {
  color: "black",
  background: "lightskyblue",
  bold: false,
  ignoreCase: true,
  wholeWord: true
};

$("#searchInput").keyup(function() {
  var searchVal = $(this).val();
  // console.log("value", searchVal);
  if (!searchVal || searchVal === "") {
    console.log("no value", searchVal);
    if (searchVal === "") return;
  } else {
    console.log("value", searchVal);
    $(".searchtext").each(function() {
      $(this).highlight(searchVal, option);
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="searchInput" class="search-box" type="text" placeholder="Search"><i type="reset" class="fas fa-search"></i></input>
<p class="searchtext">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

【问题讨论】:

  • 您必须在每次运行时删除您添加的所有 &lt;span&gt; 元素。
  • 谢谢@Titus。这行得通。
  • 我已经发布了答案。
  • 代码可以正常工作,直到您将 HTML 加入其中。比它不是一个简单的带有查找/替换的正则表达式。

标签: javascript jquery search


【解决方案1】:

您必须删除在每次运行时添加的所有跨度。

类似这样的:

/**
 * highlight 1.0.0
 * Licensed under MIT
 *
 * Copyright (c) 2016 yjteam
 * http://yjteam.co.kr
 *
 * GitHub Repositories
 * https://github.com/yjseo29/highlight.js
 */

if (typeof jQuery === "undefined") {
  throw new Error("JavaScript requires jQuery");
}

+(function($) {
  "use strict";
  var version = $.fn.jquery.split(" ")[0].split(".");
  if (
    (version[0] < 2 && version[1] < 9) ||
    (version[0] == 1 && version[1] == 9 && version[2] < 1)
  ) {
    throw new Error("JavaScript requires jQuery version 1.9.1 or higher");
  }
})(jQuery);

+(function($) {
  $.fn.highlight = function(word, options) {
    $(".highlightLibSpan").replaceWith(function(){
       return $(this).text();
    })
    
    var option = $.extend(
      {
        background: "#ffff00",
        color: "#000",
        bold: false,
        class: "",
        ignoreCase: true,
        wholeWord: true
      },
      options
    );
    var findCnt = 0;

    if (this.length == 0) {
      throw new Error("Node was not found");
    }

    var $el = $('<span class="highlightLibSpan" style="color:' + option.color + ';"></span>');
    if (option.bold) {
      $el.css("font-weight", "bold");
    }
    if (option.background != "") {
      $el.css("background", option.background);
    }
    if (option.class != "") {
      $el.addClass(option.class);
    }

    if (option.wholeWord) {
      word = "\\b" + escapeRegExp(word) + "\\b";
    }
    var re = new RegExp(word, option.ignoreCase == true ? "gi" : "g");

    this.each(function() {
      var content = $(this).html();

      $(this).html(
        content.replace(re, function(t) {
          findCnt++;
          $el.text(t);
          return $el.get(0).outerHTML;
        })
      );
    });
    return findCnt;

    function escapeRegExp(string) {
      return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
    }
  };
})(jQuery);



// highlight search terms in content
var searchCnt = 0;

var option = {
  color: "black",
  background: "lightskyblue",
  bold: false,
  ignoreCase: true,
  wholeWord: true
};

$("#searchInput").on("input", function() {
  var searchVal = $(this).val();
  $(".searchtext").each(function() {
    $(this).highlight(searchVal, option);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="searchInput" class="search-box" type="text" placeholder="Search"><i type="reset" class="fas fa-search"></i></input>
<p class="searchtext">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

我所做的更改是添加

$(".highlightLibSpan").replaceWith(function(){
   return $(this).text();
})

在库函数的开头,并将highlightLibSpan 类添加到库创建的所有&lt;span&gt; 元素中。

此外,您可能应该使用input 事件而不是使用keyup 事件来解释其他事件,例如paste

【讨论】:

    【解决方案2】:

    根据@Titus 的建议,我的解决方法是在内容中的 span 标签上添加一个 removeAttr 调用:

    // highlight search terms in content
    $("#searchInput").keyup(function() {
      var option = {
        color: "black",
        background: "lightskyblue",
        bold: false,
        ignoreCase: true,
        wholeWord: true
      };
      var searchVal = $(this).val();
      // console.log("value", searchVal);
      if (!searchVal || searchVal === "") {
        console.log("no value", searchVal);
            $(".searchtext")
             .find("span")
             .contents()
             .unwrap();
        return;
      } else {
        console.log("value", searchVal);
        $(".searchtext").each(function() {
          $(this).highlight(searchVal, option);
        });
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-10
      • 2020-03-12
      • 1970-01-01
      • 1970-01-01
      • 2019-02-01
      • 1970-01-01
      • 2021-12-15
      • 2021-02-06
      相关资源
      最近更新 更多