简体   繁体   中英

Highlight live search results

I'm trying to highlight the text that matches the query in a live search using jquery.highlight . The live search works fine but the styling for the highlighting applies then it disappears. Am I doing something wrong?

JQuery

$(document).ready(function() {
    $("#search").bind("keyup", function() {
    var form = $(this).parents("form");
    var query = $(this).val();
    var formData = form.serialize();

    $.post("/questions/new/search", formData, function(html) { 
      $("#questionList").html(html);
    });

    $(".question").highlight(query);
  });
});

HTML

<form action="/questions" method="get">
    <input id="search" name="search" type="text" />
</form>

<div id="questionList">
    <div class="question">What is the 1 + 1?</div>
    <div class="answers">2</div>
</div>

Yes, you should execute $(".question").highlight(query) in the http request response handler right after $("#questionList").html(html) this way:

$(document).ready(function() {
    $("#search").bind("keyup", function() {
    var form = $(this).parents("form");
    var query = $(this).val();
    var formData = form.serialize();

    $.post("/questions/new/search", formData, function(html) { 
      $("#questionList").html(html);
      $(".question").highlight(query);
    });

  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM