假设我有以下 HTML 代码
<div class="answers">
He<b>y</b> <span class='doesntmatter'>eve</span>ryone
</div>
我有以下数组:
['correct','correct','incorrect','correct','correct','correct','incorrect','incorrect','correct','correct','incorrect']
我想转换这段 HTML 代码,并为数组中的类的每个字母添加一个跨度(我将解释)
所以,我想将字母 H 转换为 <span class='correct'>H</span>
e 说:<span class='correct'>e</span>
你可以说:<span class='incorrect'>y</span>
e 说:<span class='correct'>e</span>
等等。我想确保保留原始 HTML,<br>
标签,<p>
标签之类的。由于这个原因我不能使用 jQuery(element).text() (因为它破坏了标签)。
有人知道我该怎么做吗?非常感谢。
最佳答案
var arr = ['correct','correct','incorrect','correct','correct','correct','incorrect','incorrect','correct','correct','incorrect'],
answer = document.getElementsByClassName("answers")[0],
rex = /(?=\w|<)(?=[^>]*(?:<|$))/,
i = 0, class;
answer.innerHTML = answer.innerHTML.split(rex).map(function(p) {
if (p.indexOf('>')) return p;
class = arr[i++] || 'notDefined';
return '<span class="' + class + '">' + p + '</span>';
}).join('');
非单词字符不会换行。如果文本包含 html 实体(例如
),则需要一些额外的工作。
关于javascript - 用跨度替换文档中的特定字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26407934/