首页 > 解决方案 > 带有jquery的Javascript高亮功能不起作用

问题描述

我正在尝试使用 jQuery 构建一个“简单”的突出显示功能。出于某种原因,它使我的 HTML 重复,我不知道为什么。我想做的就是在搜索栏中输入搜索文本,并在我输入时突出显示标签中的文本。

有什么想法吗?绝望的...

这是HTML和JS

function hiLite(searchWords) {
  if (searchWords) {
    var content = $("p").text();
    var regExp = new RegExp(searchWords, "ig");
    var matches = content.match(regExp);
    if (matches) {
      $("p").html(content.replace(regExp, function(match) {
        return "<span class='highlight'>" + match + "</span>";
      }));
    } else {
      $(".highlight").removeClass("highlight");
    }
  } else {
    $(".highlight").removeClass("highlight");
  }
};
$("#searchBar").keyup(function() {
  var userInput = $(this).val().toLowerCase();
  hiLite(userInput);
});
<!doctype html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <link rel="stylesheet" href="photo_filter.css" type="text/css">
</head>

<body>
  <div class="search">Search:
    <input type="text" id="searchBar">
  </div>
  <div id="results">
    <p>some text is here</p>
    <p>other kinds</p>
    <p>even more</p>
  </div>
</body>

</html>

标签: javascriptjquery

解决方案


解决方案2:

添加了基于搜索文本突出显示文本的条件

JS代码:

 function hiLite(searchWords){

        if(searchWords){
        var content = $("p").text();
        var regExp = new RegExp(searchWords, "ig");
        var matches = content.match(regExp);

       if(matches){
                        $('#results p').each(function() {
                        var test = '<span class="highlight">'+searchWords+'</span>';
                        var text = $(this).text();
                        $(this).html(text.replace(regExp, test)); 
                    });
            }

        } 
    };


$("#searchBar").keyup(function(){
 var userInput = $(this).val().toLowerCase();
 hiLite(userInput); 
});

HTML 代码:

<div class="search">Search:     
<input type="text" id="searchBar">    
</div>

<div id="results">

    <p>some text is here</p>
    <p>other kinds</p>
    <p>even more</p>

</div>

CSS:

.highlight{
  color:red
}

JSF中


推荐阅读