【发布时间】:2016-06-05 23:26:34
【问题描述】:
来自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>
【问题讨论】:
-
您未发布的代码可能有问题。
-
根据您发布的代码示例,仅斜体完成。
-
对此我很抱歉,我认为参考我正在谈论的帖子就足够了。用户 Filype 回答了我的问题,但我一定会记得将来始终包含我自己的代码...
标签: javascript jquery css