使用jQuery在URL末尾添加变量

时间:2013-04-09 16:16:58

标签: javascript jquery html url variables

到目前为止,我已经完成了

jQuery的:

function addURL(element)
{
var baseZipCode = 48180;
$(element).attr('href', function() {
    return this.href + baseZipCode;
});
}

HTML:

<a onclick="addURL(this)" href="http://www.weather.com/weather/today/" target="_blank">Click this</a>

我的问题是当用户点击链接并且新窗口打开时一切正常,但是当用户再次点击链接而没有刷新时,该变量会被添加两次到链接。

例如:

第一次: http://www.weather.com/weather/today/48180

第二次: http://www.weather.com/weather/today/4818048180

在您进行页面刷新之前它不会正常运行,任何帮助都将不胜感激。提前致谢

4 个答案:

答案 0 :(得分:1)

将您的addURL功能替换为

function addURL(element)
{
    var baseZipCode = '48180';
    if (element.href.slice(-baseZipCode.length) !== baseZipCode){
        element.href += baseZipCode;
    }
}

没有涉及jQuery ..

答案 1 :(得分:1)

您可以使用jQuery.fn.one

进行尝试

使用Javascript:

  jQuery("a").one("click", function(){ // Set a handler that execute once
        var baseZipCode = 48180;
        this.href += baseZipCode; //same as "this.href = this.href + baseZipCode"
    });

HTML:

<a href="http://www.weather.com/weather/today/" target="_blank">Click this</a>

也许您需要将一些类添加到&lt; a&gt;标签与其他标签不同

答案 2 :(得分:0)

这应该是:

function addURL(element)
{
    var baseZipCode = 48180;
    element.href = (element.href + baseZipCode)
        .replace(baseZipCode + baseZipCode, baseZipCode);
}

答案 3 :(得分:0)

return this.href.indexOf(baseZipCode) != -1 ? this.href : this.href + baseZipCode;
相关问题