使用jQuery动态包装anchor元素中的单词

时间:2014-02-26 06:26:35

标签: jquery replace

我正在尝试编写一个使用jQuery动态包装锚标签中的单词的函数。具体来说,我希望博客文章中每个作者姓名的实例链接到他们帖子的页面。我现在所拥有的似乎并没有表明任何错误,但它并没有用链接替换我的名字:

( function( $ ) {
  jQuery(document).ready(function ($) {
    function linkAuthorRefs( authors, newName ) {
      for( i = 0; i < authors.length; i++ ) {
        var author = authors[i],
            regExAuthor = "/" + author + "/gi",
            $elements = $( '.entry-content p:contains( "' + author + '" ), .entry-summary p:contains( "' + author + '" )' );
        if( ! newName ) { var newName = author.toLowerCase(); }
        for( j = 0; j < $elements.length; j++ ) {
          e = $elements[j];
          e.html(e.html().replace( regExAuthor, '<a title="View all posts by ' + newName + '" href="http://aaronandrebekah.com/?category=' + newName + '" rel="author">' + author + '</a>' ) );
        }
      }
    }
    var authorNames = [ "Aaron", "Rebekah" ];
    linkAuthorRefs( authorNames );
    linkAuthorRefs( [ "Bekah" ], "rebekah" );
  });
} )( jQuery );

1 个答案:

答案 0 :(得分:0)

感谢您的建议。经过更多的研究,以下效果很好!

$.each( [ "Aaron", "Rebekah" ], function( i, j ) {
  var author = j,
      authorLower = author.toLowerCase(),
      regExAuthor = RegExp( "\\b" + author + "\\b", "gi"),
      anchoredText = '<a title="View all posts by ' + authorLower + '" href="http://aaronandrebekah.com/?category=' + authorLower + '" rel="author">' + author + '</a>',
      $elements = $( '.entry-content p, .entry-summary p' );
  $elements.each( function() {
    var $par = $( this );
    $par.html( $par.html().replace( regExAuthor, anchoredText ) );
  });
});