2011-09-21 109 views
3

我有3个href具有不同的结构,并且它们都具有相同的硬编码参数(在此示例中value = somevalue-abc)。使用jQuery更新href中的querystring值

如何更新链接并用新值覆盖该值?

jQuery的

$(document).ready(function() { 

    $('a').click(function() { 

     var $newValue = 'newvalue'; 

     //here a function that overwrites the parameter 'somevalue-abc' with $newValue 

    }); 

}); 

HTML

<a class="demo" href="http://www.mydomain.com/page.aspx?demo&value=somevalue-abc">link 1</a> 
<a class="real" href="http://www.mydomain.com/?value=somevalue-abc#go=yes">link 2</a> 
<a class="outgoing" href="http://www.mydomain.com/page.aspx?value=somevalue-abc">link 3</a> 

回答

8

尝试:

$(document).ready(function() { 
    $('a').click(function() { 
     var $newValue = 'newvalue'; 
     $(this).attr('href',$(this).attr('href').replace('somevalue-abc', $newValue)); 
    }); 
}); 
+0

完美的作品(和这么简单我可以拍自己没有找到这个我自己)。 Thx !! – NicoF

5
$('a').click(function() { 
    var newValue = 'newvalue'; // pls don't use a $ on variables that aren't jquery objects 
    var src = $(this).attr('href'); 
    $(this).attr('href', src.replace(/somevalue\-abc/, newvalue)); 
});