2014-03-01 58 views
0

我有很多下载链接是为我的用户在我的网站中提供的,我希望为这些链接添加特定的参考链接。例如:jQuery在链接中添加域名

http://rapidgator.net/file/xxxx 

现在我想用jQuery在每个外部链接的链接前添加我的对象链接。我搜索,只发现了jQuery为attr

jQuery('a[href*="http://"]:not([href*="http://www.mysite.com"])').attr('rel', 'nofollow'); 

但在我的情况下,我想添加我的域名中的链接的前面,这样网址:

<a href="http://rapidgator.net/file/xxxx">http://rapidgator.net/file/xxxx</a> 

将变为:

<a href="http://myspecificdomain.com?ref=http://rapidgator.net/file/xxx">http://rapidgator.net/file/xxxx</a> 

这可以使用jQuery来完成吗?

回答

0

其实你就要成功了,你已经可以得到你想要的所有元素,你需要做的是循环他们并更换href属性:

$('a[href*="http://"]:not([href*="http://myspecificdomain.com"])').each(function(index){ 
    $(this).attr('href',"http://myspecificdomain.com?ref="+$(this).attr('href')) 
}); 

活生生的例子:http://jsfiddle.net/63pMH/1/

但尽管如此,这不会找到链接开始“WWW”,除非所有的链接没有www前缀

+0

谢谢你,我记住这是非常简单的,而不是与实际演示困惑锚.. 。谢谢Sari Alalen –

+0

这实际上是我12分钟后发布的答案。 – Charlie

0

这将会发现所有以http://开头的链接,但尚未包含指向您网站的链接。您可以相应地编辑该语句。然后,它通过每个环节的循环,捕获当前href,然后追加到了最终的ref文字:

$('a[href*="http://"]:not([href*="http://www.mysite.com"])').each(function(){ 
    var current = $(this).attr("href"); 
    $(this).attr("href", "http://myspecificdomain.com?ref=" + current); 
}); 

Example

0

是的,它可以使用jQueryattr函数来完成。

我们将读取链接的'href属性并以您所需的格式http://myspecificdomain.com?ref=original_link形成一个新字符串并更新href

步骤

  1. 选择要操作的链接。它们可以是所有链接,由id标识的单个链接或由class标识的多个链接,或更高级的选择器(documentation)。
  2. 阅读href,操作它并更新它。

编辑:代码和演示的jsfiddle更新管理不开始链接的 'http://'(由萨里Alalem的建议)。下面将扫描所有链接,并操纵所有,但http://myspecificdomain.com

jQuery代码:

$(document).ready(function() { 
     $('a').each(function(index) { 
      var originalUrl = $(this).attr('href'); 

      if (originalUrl != 'http://myspecificdomain.com') { 
       var modifiedUrl = 'http://myspecificdomain.com?ref=' + $(this).attr('href'); 
       $(this).attr('href', modifiedUrl) 
      } 

      alert($(this).attr('href')); // debug code, remove 
     }); 
    }); 

JSFiddle demo