2012-10-03 34 views
0

我使用ligatures.js到我的网站有一些字符组合的结扎线内替换文本。例如,'五'中的'fi'。应用结扎与jQuery只链接文本,而不是链接的href

这是我的例子:http://jsfiddle.net/vinmassaro/GquVy/

当你运行它,你可以选择输出文本和看到,在“十二五”的“网络连接”已经成为一个字符如预期。如果您复制链接地址及贴吧,你会看到在href部分已经被替换,以及:

/news/here-is-a-url-with-%EF%AC%81ve-ligature 

这是意外,并打破了链接。我怎样才能替换只是链接的文本,而不是href部分?我试过使用.text()和.not()没有运气。提前致谢。

+1

,现在我知道一个连字是什么! –

回答

1

我认为你可以使用合适的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/

+0

谢谢,效果很好! – Vincent

+0

这只适用于h3内的链接,或者不包含任何链接的h3元素。 – bfavaretto

0

要应用的功能,整个标题的innerHTML,其中包括锚的href属性。这应该为你的提琴例如工作:

​​

然而,它只会在里面的标题联系工作,我不知道这是你在找什么。如果你想要的东西,一定元素中的任何内容工程(含任何级别标记嵌套的),那么你就需要一个递归方法。这里有一个想法,这基本上是普通的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', '&#xfb03;') 
      .ligature('ffl', '&#xfb04;') 
      .ligature('ff', '&#xfb00;') 
      .ligature('fi', '&#xfb01;') 
      .ligature('fl', '&#xfb02;'); 
}); 

,应该在内容像这样工作:

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

+0

谢谢,但我确实需要将它应用于不是链接的元素,所以我希望有另一种解决方案。 – Vincent

+0

@Vincent其他元素有什么问题? – svillamayor

+0

我需要将它应用于链接以及非链接,正是我所说的。它应该处理标题是否包含链接。 – Vincent