javascript - 将一些文本设为粗体和一些斜体

标签 javascript jquery css

来自 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']
});

在这里查看工作版本: http://jsbin.com/xamisohehi/edit?html,js,output

关于javascript - 将一些文本设为粗体和一些斜体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37647772/

相关文章:

javascript - 我可以将 javascript 模块与 "regular"javascript 混合使用吗?

javascript - 如何将变量内容作为参数传递给函数

css - 使用 CSS 将图标与文本(RTL 站点)的右侧对齐

jquery - 为移动设备调整 reCaptcha 的大小/样式

javascript - 字母解码Javascript

javascript - cytoscape js dijkstra 方法在回调中抛出 TypeError

javascript - Protractor/WebDriverJS 中的 by.js 定位器是什么?

javascript - 在 jQuery 中使用多个具有相同名称的单选框

jquery - 在 setTimeout 中传递 $(this)

html - Shopify 的 SVG Sprite 解决方法