【发布时间】:2021-02-26 16:26:24
【问题描述】:
我正在使用这个脚本来包装一个带有 span 标签的特定单词。如果单词是 href 属性,我需要排除替换。
// Prevent orphaned words for strings with more than 3 words
$("p:not(.form-row),h1,h2,h3,h4,h5,h6").each(function (i, e) {
var text = $(e).html();
text = text.trim().split(' ');
if (text.length > 3) {
var lastWord = text.pop();
text = text.join(' ') + " " + lastWord;
$(e).html(text);
}
// Wrap all occurrences of word-123 with a span so it doesn't break to two lines
$(e).html( $(e).html().replace(/word-123/ig, '<span class="nowrap">$&</span>') );
});
当单词在href 中时,href 中的单词会被换行,从而破坏href。所以
Lorem ipsum dolor sit amet, <a href="word-123">consectetur</a> adipiscing elit.
呈现为
Lorem ipsum dolor sit amet, <a href="<span class="nowrap">word-123</span>">consectetur</a> adipiscing elit.
【问题讨论】:
-
你为什么要从 HTML 开始?
var text = $(e).html();只需使用.text().. 并在此处将其插入为 html:$(e).html(text);。当您使用它时,这将实现 href 属性和任何其他 HTML 属性。 -
另外:
:not(a[href]) -
这能回答你的问题吗? jQuery: Find text and replace with HTML
-
用 .text() 替换 var text = $(e).html() 会完全删除链接。
-
最近有人为此提供了他们自己的问题的答案 - 去给他们一个赞成票:stackoverflow.com/a/66372448/2181514
标签: javascript jquery