用jquery搜索单词并突出显示

时间:2015-07-23 15:42:29

标签: javascript jquery html highlight

我在jQuery中编写了一个提供搜索功能的javaScript文件。我试图弄清楚如何突出这个词。贝娄是代码。

Filter.js:

(function ($) {
  // custom css expression for a case-insensitive contains()
  jQuery.expr[":"].Contains = jQuery.expr.createPseudo(function(arg) {
    return function( elem ) {
        return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
});


function listFilter(header, list, title) { 
   // header is any element, list is an unordered list, title is any element
   // create and add the filter form to the header
   // create a button for collapse/expand to the title

var form = $("<form>").attr({"class":"filterform","action":"#"}),
    button = $("<input>").attr({"class":"rest", "type":"submit", "value":"Collapse All", "id":"switch"}),
    input = $("<input>").attr({"class":"filterinput","type":"text", "placeholder":"Search"});

$(form).append(input).appendTo(header); //add form to header
$(title).append(button); //add button to title

 //on click function for collapse/expand all
$("#switch").click(function(){
    if($(this).val() == "Collapse All"){
        $(".filterinput").val("");
        $(this).val("Expand All");
        $("div.content div.markdown").parent().parentsUntil(list).hide();
        $(list).find("span.path").parentsUntil(list).show();
        $(list).find("ul.endpoints").css("display", "none");
    }
    else{
        $(".filterinput").val("");
        $(this).val("Collapse All");
        $("div.content div.markdown").parent().parentsUntil(list).hide();
        $(list).find("span.path").parentsUntil(list).show();
    }
});

$(input)
  .change( function () {
    var filter = $(this).val();
    if(filter) {
      // this finds a single string literal in div.markdown,
      // and hides the ones not containing the input while showing the ones that do
        $(list).find("div.content div.markdown:not(:Contains(" + filter + "))").parent().parentsUntil(list).hide();
        $(list).find("div.content div.markdown:Contains(" + filter + ")").parent().parentsUntil(list).show();
    } 
    else {
        $("div.content div.markdown").parent().parentsUntil(list).hide();
        $(list).find("span.path").parentsUntil(list).show();
        $(list).find("ul.endpoints").css("display", "none");
    }
    return false;
  })
.keyup( function () {
    // fire the above change event after every letter
    $(this).change();
});
}
   //ondomready
   setTimeout(function () {
    listFilter($("#header"), $("#resources"), $("#api_info"));
   }, 250);
}(jQuery));

我想要操作的html是由另一个JS文件动态创建的,所以我需要在完全呈现后操纵DOM。我将关注的html呈现为低于标题,特别是单词in(div class =&#34; markdown&#34;)。

的index.html:

<div class="content" id="connectivitypacks_get_connectivitypacks_content">
    <h4>Description</h4>
    <div class="markdown"><p>Response will return details for the connectivity packs based on the ID.</p>
        <h2 id="keywords">Keywords</h2>
        <p> foo, bar, helloWorld, java</p>
    </div>
</div>

2 个答案:

答案 0 :(得分:4)

以下是使用降价的示例。

  1. 使用您搜索的单词创建正则表达式。
  2. 获取.markdown
  3. 的html
  4. 将该字词替换为<span class="marker">"+ word +"</span>。因此,这会在您搜索的单词周围创建一个span标记。
  5. 根据需要创建css以设置单词样式。
  6. function highlight(word) {
      var element = $('.markdown');
      var rgxp = new RegExp(word, 'g');
      var repl = '<span class="marker">' + word + '</span>';
      element.html(element.html().replace(word, repl));
    
    }
    
    highlight('details');
    .marker {
      background-color: yellow;
      font-weight: bold;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="content" id="connectivitypacks_get_connectivitypacks_content">
      <h4>Description</h4>
      <div class="markdown">
        <p>Response will return details for the connectivity packs based on the ID.</p>
        <h2 id="keywords">Keywords</h2>
        <p>foo, bar, helloWorld, java</p>
      </div>
    </div>

答案 1 :(得分:1)

看看mark.js。它可以在特定上下文中突出显示此类搜索词。在您的示例中,JavaScript看起来像:

var searchTerm = $("#theInput").val();

// Search for the search term in your context
$("div.markdown").mark(searchTerm, {
    "element": "span",
    "className": "highlight"
});

和CSS部分:

span.highlight{
    background: yellow;
}