我想制作一个文本突出显示工具:我有我的段落,qtext
而我要在段落中突出显示的单词是answerCodes
。我想为他们添加一个span类,并在段落中突出显示它们。任何想法都会有所帮助!
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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句