【问题标题】:Update querystring value in href with jQuery使用 jQuery 更新 href 中的查询字符串值
【发布时间】:2011-09-21 06:33:35
【问题描述】:

我有 3 个具有不同结构的 href,它们都具有相同的硬编码参数(在此示例中 value=somevalue-abc)。

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

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>

【问题讨论】:

    标签: jquery query-string


    【解决方案1】:

    试试:

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

    【讨论】:

    • 工作完美(如此简单,我可以自己拍自己却找不到这个)。谢谢!!
    【解决方案2】:
    $('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));
    });
    

    【讨论】:

      猜你喜欢
      • 2012-03-26
      • 1970-01-01
      • 1970-01-01
      • 2013-06-17
      • 2020-01-11
      • 2020-12-21
      • 1970-01-01
      • 2012-10-26
      相关资源
      最近更新 更多