[英]Make some text bold AND some italic
From this question I got the code to find text, wrap it in, and make it bold, which works (I used Jahu's answer , the one with a jsbin). 从这个问题我得到了代码来查找文本,将其包装,并使其变为粗体,这是有效的(我使用了Jahu的答案 ,带有jsbin的答案 )。 When I copy it to another file and change it to make the text italic, it works. 当我将它复制到另一个文件并更改它以使文本斜体时,它的工作原理。
However, when I put the both of them in the same file (even in different <script>
tags) only the bold one happens. 但是,当我将它们放在同一个文件中时(即使在不同的<script>
标签中),只会出现粗体。 Anyone know why? 谁知道为什么?
$.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>
The way it was implemented prevents you from changing multiple tags in a sequence because the element's content was converted into text. 它的实现方式阻止您更改序列中的多个标记,因为元素的内容已转换为文本。
Here's what I have done: 这就是我所做的:
// 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);
How it's run: 怎么运行:
$('p').wrapInTag({
tag: 'em',
words: ['world', 'red']
});
$('p').wrapInTag({
tag: 'strong',
words: ['is']
});
See the working version here: http://jsbin.com/xamisohehi/edit?html,js,output 请参阅此处的工作版本: http : //jsbin.com/xamisohehi/edit?html,js,output
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.