我想制作一个文字荧光笔:我在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...
}
答案 0 :(得分:1)
根据答案代码生成正则表达式并替换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>
答案 1 :(得分:0)
使用 RegExp 替换。
for (var i=0; i< answerCodes.length; i++) {
qText = qText.replace(new RegExp(answerCodes[0], 'g'), '<span class="highlight">$1</span>');
}