我正在使用ligatures.js用一些字符组合的连字替换我的站点中的文本。例如,'five‘中的'fi’。
下面是我的示例:http://jsfiddle.net/vinmassaro/GquVy/
当您运行它时,您可以选择输出文本,并看到'five‘中的'fi’变成了预期的一个字符。如果复制并粘贴链接地址,您将看到href部分也已被替换:
/news/here-is-a-url-with-%EF%AC%81ve-ligature这是意想不到的,并破坏了链接。如何才能只替换链接的文本,而不替换href部分?我尝试过使用.text()和.not(),但没有成功。提前谢谢。
发布于 2012-10-03 23:25:18
我认为您可以使用适当的jQuery选择器来解决这个问题
$('h3 a, h3:not(:has(a))')
.ligature('ffi', 'ffi')
.ligature('ffl', 'ffl')
.ligature('ff', 'ff')
.ligature('fi', 'fi')
.ligature('fl', 'fl');请参阅http://jsfiddle.net/GquVy/7/
发布于 2012-10-03 22:50:34
您将该函数应用于整个标题的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>http://jsfiddle.net/JjLZR/
https://stackoverflow.com/questions/12710898
复制相似问题