从这个问题中,我得到了查找文本,将其包装并使其变粗的代码,这行得通(我使用Jahu的答案,即带有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']
});
在此处查看工作版本:http : //jsbin.com/xamisohehi/edit?html,js,output
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句