2014-08-27 72 views
-4

我只是想在加载页面时更改所有的href链接。使用JavaScript或JQuery或任何其他方法。如何更改页面中所有链接的href?

我的一个页面上的链接都喜欢

<a href="http://example.com/book"> 
<a href="http://example.com/sheo"> 
<a href="http://example.com/belt"> 

进入

<a href="http://a.example.com/book"> 
<a href="http://a.example.com/sheo"> 
<a href="http://a.example.com/belt"> 

是否有可能使用替代(我只是猜测)? 请同时查看查询字符串如何不更改,只更改主机名称。 抱歉有混淆。

+1

你的意思是,如果你有通过'http://cnn.com'你想把它改成'http:// a.cnn.com',或者是'http:// example.com',因为我想知道这些答案是否会跳过枪? – Andy 2014-08-27 09:38:37

+1

那么,例如,指向'http:// m.example.com /'的链接呢?作为一个附录,对于这个问题,我不知道是否应该冷静下来*所有事情*,或者投票表决为“不清楚你要问什么”。 – 2014-08-27 09:39:26

+1

我去投票保留;似乎不公平惩罚那些试图帮助解决不明确问题的人。 – 2014-08-27 09:43:35

回答

0

这改善了Jhecht的答案,让你同时保持第二部分更换URL的第一部分:

$('a').each(function(i,link){ 
    var reg = /(http:\/\/example.com\/)(.*)/ 
    var newlink = link.href.replace(reg, 'http://m.example.com/$2') 
    link.href = newlink; 
    link.innerHTML = newlink; 
}); 

DEMO

+0

你的答案是非常接近我想,我使用 test1 test2 Racheal 2014-08-27 10:34:29

+0

@Racheal,我已经更新了我的答案来取代链接文本太多,如果这就是你以后是什么也。 – Andy 2014-08-27 10:38:22

+0

你好安迪,我已经实现了你的代码,它没有工作,我已经检查了所有的代码,一次又一次,即使在简单的测试文件,它没有工作,我也使用最新的jquery文件。 – Racheal 2014-08-27 10:46:48

0

尝试用在文件准备功能,下面的jQuery代码:

$(document).ready(function() { 
    $('a').attr('href', 'http://a.example.com'); 
    }); 
+0

不需要循环每个'a'元素。 – 2014-08-27 09:38:48

0

做得一样:

$('a').attr('href','http://a.example.com'); 

就是这样。

0

使用jQuery:

$("a").attr("href", "http://a.example.com"); 

或者,如果你希望这些链接到http://example.com

$('a[href="http://example.com"]').attr("href", "http://a.example.com"); 
0

尝试:

$(document).ready(function() { 
$('a[href*="Yourpage.html"]').prop('href' , 'http://a.example.com'); 
}); 
1

应该做你想要什么,并留下完整地跟踪请求的链接。

$('a').each(function(i,link){ 
    link.href = link.href.replace('http://example.com/','http://a.example.com/'); 
}); 
+1

我认为这应该做你的工作.. – 2014-08-27 09:41:35

+0

但如何更改与查询字符串。 http://example.com/college_bookstore/textbook/,也有很多不同的查询字符串的链接,但具有相同的基础url示例。com – Racheal 2014-08-27 09:55:02

+1

如果您尝试将其中包含“http:// example.com /”的网站中的所有链接更改为“http:// a.example.com /”,那么是的,这是应该管用。没有更多的细节,我不能更具体地解决你的问题。 – Jhecht 2014-08-27 10:05:56

相关问题