如何根据查询从搜索结果中突出显示单词?

时间:2018-10-23 14:14:46

标签: python html django highlight

我希望我用来搜索结果的单词在结果中突出显示。我将如何进行呢?

我看过使用JS的示例,但是它们似乎不适用于我的代码。

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,
})

1 个答案:

答案 0 :(得分:0)

我不确定您的问题是否与python有关,还是包含使用其他技术。

但是,我建议您使用:

jQuery Highlight Plugin

基本上,您必须使用以下命令导入jquery

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

还有highlight script,您可以在这里下载: https://johannburkard.de/resources/Johann/jquery.highlight-5.js

然后,一旦导入jquery highlight plugin,您就可以定义添加行为的单词数组:

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