来自 this question我得到了代码来查找文本,将其包装起来并使其变为粗体,这很有效(我使用了 Jahu's answer ,带有 jsbin 的代码)。当我将它复制到另一个文件并更改它以使文本变为斜体时,它起作用了。
但是,当我将它们放在同一个文件中时(即使在不同的 <script>
标签中),只会出现粗体。有人知道为什么吗?
$.fn.wrapBoldTag = function(opts) {
// https://stackoverflow.com/a/1646618
function getText(obj) {
return obj.textContent ? obj.textContent : obj.innerText;
}
var tag = opts.tag || 'strong',
words = opts.words || [],
regex = RegExp(words.join('|'), 'gi'),
replacement = '<' + tag + '>$&</' + tag + '>';
// https://stackoverflow.com/a/298758
$(this).contents().each(function() {
if (this.nodeType === 3) //Node.TEXT_NODE
{
// https://stackoverflow.com/a/7698745
$(this).replaceWith(getText(this).replace(regex, replacement));
} else if (!opts.ignoreChildNodes) {
$(this).wrapBoldTag(opts);
}
});
};
$('p').wrapBoldTag({
"words": ["blue"]
});
$('p').wrapBoldTag({
"words": ["edit"],
"ignoreChildNodes": true
});
$.fn.wrapInTag = function(opts) {
var tag = opts.tag || 'strong',
words = opts.words || [],
regex = RegExp(words.join('|'), 'gi'),
replacement = '<' + tag + '>$&</' + tag + '>';
return this.html(function() {
return $(this).text().replace(regex, replacement);
});
};
$('p').wrapInTag({
tag: 'u',
words: ['sky']
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>The sky is blue.</p>
最佳答案
它的实现方式可防止您更改序列中的多个标签,因为元素的内容已转换为文本。
这是我所做的:
// stips out tags, which causes issues when onverting 2 tags
// return $(this).text().replace(regex, replacement);
// use the html contents of the element
return $(this).html().replace(regex, replacement);
它是如何运行的:
$('p').wrapInTag({
tag: 'em',
words: ['world', 'red']
});
$('p').wrapInTag({
tag: 'strong',
words: ['is']
});
关于javascript - 将一些文本设为粗体和一些斜体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37647772/