我想制作一个文本荧光笔:我的段落位于 qtext
中,而我想要在段落中突出显示的单词位于 answerCodes
中。我想为它们添加一个跨度类并在段落中突出显示它们。任何想法都会有所帮助!
var answerCodes = $('[id*="_label"]').text();
var qText = $('.question_text').html();
for (var i=0; i<answerCodes.length; i++) {
need to put something here...
}
最佳答案
根据答案代码生成正则表达式并替换html内容。
// generate regex
var reg = new RegExp(
// get all answer code elements
$('[id*="_label"]')
// iterate over them
.map(function() {
// get text content and
// escape symbols which has special meaning in regex
return $(this).text().replace(/[|\\{}()[\]^$+*?.]/g, '\\$&');
})
// get result as array
.get()
// join them with pipe symbol
.join('|'),
// set global modifier for global match
'g');
// iterate over p
$('.question_text').html(function(i, html) {
// replace the question code with span wrapped content
return html.replace(reg, '<span class="highliter">$&</span>');
});
var reg = new RegExp(
$('[id*="_label"]').map(function() {
return $(this).text().replace(/[|\\{}()[\]^$+*?.]/g, '\\$&');
}).get().join('|'), 'g');
$('.question_text').html(function(i, html) {
return html.replace(reg, '<span class="highliter">$&</span>');
});
.highliter {
color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label id="_label1">abc</label>
<label id="_label1">test</label>
<div class="question_text">a a a a abc bb b test dd abc fff</div>
关于jquery - JQuery 段落中的单词高亮显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41565545/