【问题标题】:Make some text bold AND some italic使一些文本加粗和一些斜体
【发布时间】: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


【解决方案1】:

它的实现方式阻止您更改序列中的多个标签,因为元素的内容已转换为文本。

这是我所做的:

// 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

【讨论】:

  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-20
  • 1970-01-01
  • 1970-01-01
  • 2016-06-23
相关资源
最近更新 更多