简体   繁体   中英

How can I highlight words from my search result based on my query?

I would like the words i used to search for results to be highlighted in the results. How would i go on about doing this?

I have looked at examples using JS but they don't seem to work with my code.

html:

(Search)
<input type="text" name="q" placeholder="Search..." required  value="{{ query|escape }}" size="100" autofocus>
<input class="buttonCopy button1" type="Submit" value="Search">

(Results)
{% for resp in results %}
    <tr>
        <td style="border: 1px solid">{{ resp.Question.Statement }}</td>
        <td style="width: 70%; border: 1px solid"><div id="resp{{forloop.counter}}" style="height: 200px;overflow-y:auto;overflow-x:hidden">{{ resp|escape|linebreaks }}</div></td>

        <td><button class="buttonCopybutton3",onclick="copyFunction('text{{forloop.counter}}')">Copy</button></td>
        <td><textarea id="text{{forloop.counter}}" style="display:block; width:0; height:0; opacity:0">{{ resp }}</textarea></td>
        <td>
            <label class="container">
            <input type="checkbox" id="chck" name="responseCheck" onClick="checkbox();" value="{{ resp }}"><br></br>
            <span class="checkmark"></span></label>
        </td>
        <td><textarea id="show" name="responseCheck" style="display:block; width:0px; height:0px; opacity:0"></textarea><br></br></td>
    </tr>
{% endfor %}

views.py:

if query:
    newquery = stopwords.strip_stopwords(query)
    terms = newquery.split()
    for term in terms:
         qset &= (
            Q(Question__Statement__icontains=term) |
            Q(Response__icontains=term)
         )
    results = Response.objects.filter(qset).distinct()
else:
    results = []
    posts = ''

return render_to_response("app/search.html", {
    "results": results,
    "query": query,
    "noOfResults": len(results),
    "username": username,
    "queryR": queryR,
    "topicList": topicList,
    "clientList": clientList,
})

I'm not sure if your question is releated with python or includes using another technology.

But, I would recommend you to use:

jQuery Highlight Plugin

Basically, you have to import jquery with:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

And the highlight script , you might download here: https://johannburkard.de/resources/Johann/jquery.highlight-5.js

And once, you import te jquery highlight plugin , you can define the array of words that you need add the behavior, with:

$("body p").highlight(["jQuery", "highlight", "plugin"]);

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