我需要使用jquery更新href值

我需要使用jquery更新页面的href值。 请将href =“http://www.google.com?gsec=account”更改为href =“http://account.google.com?gsec=account”我如何完成此操作。

这将我认为您正在寻找的整个页面中进行替换。

 // Find `` elements that contain `www.google.com` in the `href`. $('a[href*="www.google.com"]').attr('href', function(i,href) { // return a version of the href that replaces "www." with "accounts." return href.replace('www.', 'accounts.'); }); 

试一试: http //jsfiddle.net/dT8j6/


编辑:此版本允许https://和没有www.链接www.

试一试: http //jsfiddle.net/dT8j6/1/

 $('a[href*="google.com"]').attr('href', function(i,href) { return href.replace(/^http(s*):\/\/(www\.)*google.com/, 'http$1://accounts.google.com'); }); 

编辑:如果您只想更改具有gsec=account元素,请将选择器更改为$('a[href*="gsec=account"]')

让我们说你有这个:

  

你应该用这个:

  var newHref = "http://google.com"; $("#myLink").attr('href', newHref ); 

这是一个副本:

如何使用jQuery更改超链接的href

它没有提到的一个场景是,如果你在你的锚上设置一个需要更改的id,那么你可以在jQuery中使用id作为选择器。

 $("#LinkId").attr('href', "http://account.google.com?gsec=account") 

这应该有希望为您的问题提供一个非常完整的解决方案(无论如何我最好能解释它):

 $(function() { $('a').each(function() { var $this = $(this), href = $this.attr('href'); var res = href.match(/(.*?)(www)(\.google\.com.*?)([?&]gsec=)([^&]+)(.*)/); if (null != res) { // remove the "full match" entry res = res.slice(1); // replace www match with account match res[1] = res[4]; // update the href attribute $this.attr('href', res.join('')) } }); }); 

编辑:如果“帐户”是静态值,那么这也将起作用:

 $(function() { $('a').each(function() { var $this = $(this), href = $this.attr('href'); var res = href.match(/(.*?\/\/)(www)(\.google\.com.*?)([?&]gsec=account)(&?.*)/); if (null != res) { // remove the "full match" entry res = res.slice(1); // replace www match with account match res[1] = 'account'; // update the href attribute $this.attr('href', res.join('')) } }); }); 

请注意,这些解决方案假设URL中可能存在其他变体,例如http / https和其他查询字符串变量。

我想你在问题中遗漏了一些东西。 然而:

 var link = $("a"); // Or some other selector to access the link link.attr("href", "http://account.google.com?gsec=account"); 

使用jQuery的.attr()方法。 使用一个参数,它返回属性值,并设置两个参数。

 $("a#whatever").attr("href", "http://account.google.com?gsec=account"); 

如果您要更改所有链接,则:

 $(document).ready(function() { $("a").attr("href", "http://account.google.com?gsec=account"); });