使用jquery应用连字仅链接文本,而不是链接href
-
13-12-2019 - |
题
我正在使用 ligatures.js 将网站中的文本替换为某些字符组合的连字。例如,“五”中的“fi”。
这是我的例子: http://jsfiddle.net/vinmassaro/GquVy/
运行它时,您可以选择输出文本,并看到“五”中的“fi”已按预期变成了一个字符。如果复制链接地址并粘贴,您将看到 href 部分也已被替换:
/news/here-is-a-url-with-%EF%AC%81ve-ligature
这是无意的并且会破坏链接。如何仅替换链接的文本而不替换 href 部分?我尝试使用 .text() 和 .not() 但没有成功。提前致谢。
解决方案
我认为你可以使用适当的 jQuery 选择器来解决它
$('h3 a, h3:not(:has(a))')
.ligature('ffi', 'ffi')
.ligature('ffl', 'ffl')
.ligature('ff', 'ff')
.ligature('fi', 'fi')
.ligature('fl', 'fl');
其他提示
您正在将该函数应用于整个标题 innerHTML
, ,其中包括锚点的 href
属性。这应该适用于您的小提琴示例:
$('h1 a, h2 a, h3 a, h4 a').ligature( //...
但是,它仅适用于标题内的链接,我不确定这就是您正在寻找的内容。如果你想要一些有用的东西 任何 某个元素内的内容(带有 任何 标签嵌套级别),那么您将需要一种递归方法。这是一个想法,它基本上是纯 JavaScript,因为 jQuery 没有提供定位 DOM 文本节点的方法:
$.fn.ligature = function(str, lig) {
return this.each(function() {
recursiveLigatures(this, lig);
});
function recursiveLigatures(el, lig) {
if(el.childNodes.length) {
for(var i=0, len=el.childNodes.length; i<len; i++) {
if(el.childNodes[i].childNodes.length > 0) {
recursiveLigatures(el.childNodes[i], lig);
} else {
el.childNodes[i].nodeValue = htmlDecode(el.childNodes[i].nodeValue.replace(new RegExp(str, 'g'), lig));
}
}
} else {
el.nodeValue = htmlDecode(el.nodeValue.replace(new RegExp(str, 'g'), lig));
}
}
// http://stackoverflow.com/a/1912522/825789
function htmlDecode(input){
var e = document.createElement('div');
e.innerHTML = input;
return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
};
// call this from the document.ready handler
$(function(){
$('h3').ligature('ffi', 'ffi')
.ligature('ffl', 'ffl')
.ligature('ff', 'ff')
.ligature('fi', 'fi')
.ligature('fl', 'fl');
});
这应该适用于这样的内容:
<h3>
mixed ffi content
<span>this is another tag ffi <span>(and this is nested ffi</span></span>
<a href="/news/here-is-a-url-with-ffi-ligature">Here is a ffi ligature</a>
</h3>
不隶属于 StackOverflow