搜索功能不会重置为空值输入

时间:2018-08-14 12:14:31

标签: javascript jquery search

我有一个搜索和突出显示功能,该功能将内联样式添加到内容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>

2 个答案:

答案 0 :(得分:0)

在@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);
    });
  }
});

答案 1 :(得分:0)

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

类似这样的东西:

/**
 * 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类添加到库创建的所有<span>元素中。

此外,您可能不应该使用keyup事件来说明其他事件,例如粘贴