繁体   English   中英

使一些文字粗体和一些斜体

[英]Make some text bold AND some italic

这个问题我得到了代码来查找文本,将其包装,并使其变为粗体,这是有效的(我使用了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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM