[英]Dynamically highlight text in <li> based on checked checkboxes
I have a webpage that generate <li>
from a Json
object passed from a flask app route.我有一个网页,它从从Json
应用程序路由传递的Json
对象生成<li>
。 I have a set of checkboxes generated dynamically from the same Json
object.我有一组从同一个Json
对象动态生成的复选框。 What I wanted to do is highlight the words in the <li> text ... </li>
if there is a match to any checked checkbox.我想要做的是突出显示<li> text ... </li>
的单词<li> text ... </li>
如果与任何选中的复选框匹配。
This what I have done so far.这是我迄今为止所做的。
Java script to capture checked checkboxes and find matches in <li>
用于捕获选中的复选框并在<li>
查找匹配项的 Java 脚本
$(".topic-check").change(function(){
var chkTopicIDs = checkTopics();
console.log(chkTopicIDs);
list_items = document.querySelectorAll(".sent");
for (item of list_items){
var text = item.textContent;
if (new RegExp(chkTopicIDs.join("|")).test(text)){
item.classList.add("highlight");
}
else {
item.classList.remove("highlight");
}
}
});
function checkTopics(){
$checkbox = $('.topic-check');
var chkArray = [];
chkArray = $.map($checkbox, function(el){
if(el.checked){return el.id}
});
return chkArray;
}
CSS to highlight CSS 突出显示
.highlight{
background: yellow;
}
HTML template with jinja
tags带有jinja
标签的 HTML 模板
...
<ul>
{% for sent in turn['list_of_sentences'] %}
<li class="sent">{{sent['text']}}</li>
{% endfor %}
</ul>
...
<div class="card-body">
{% for topic in response['topics'] %}
<div>
<input type="checkbox" id="{{topic}}" class="topic-check" onclick="func1()" /> <label class="checkbox-inline" >{{ topic }}</label> <br/>
</div>
{% endfor %}
</div>
...
I did a sanity check to see whether I get the list of checked checkboxes.我做了一个健全性检查,看看我是否得到了选中的复选框列表。 The console displays IDs, so that part worked.控制台显示 ID,因此该部分工作正常。 But I don't see the highlighting of text regardless of checkboxes are checked.但是无论是否选中复选框,我都看不到文本的突出显示。
Side note: I also see the following error in JS console.旁注:我还在 JS 控制台中看到以下错误。 ReferenceError: func1 is not defined
1) You have a typo here: item.classList.add("highlist")
- should be highlight
correct? 1)你在这里有一个错字: item.classList.add("highlist")
- 应该highlight
正确吗?
2) onclick="func1()"
this is causing your func1 is not defined
, just remove it. 2) onclick="func1()"
这导致您的func1 is not defined
,只需将其删除即可。
3) I don't know if that's the case, but $(".topic-check").change
won't work on dynamically added HTML. 3) 我不知道是不是这样,但是$(".topic-check").change
不适用于动态添加的 HTML。 You need something like $(".card-body").on("change", ".topic-check", function)
你需要像$(".card-body").on("change", ".topic-check", function)
4) You should store new RegExp(chkTopicIDs.join("|"))
as a variable outside the loop for increased performance 4) 您应该将new RegExp(chkTopicIDs.join("|"))
为循环外的变量以提高性能
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.