在重定向之前编辑URL

时间:2014-03-20 10:12:17

标签: javascript html query-string

在此,我遇到了一个场景,我希望在重定向之前编辑href的{​​{1}}。我的方案是如果anchor tag的{​​{1}}属性不包含href,则将上一页查询字符串追加到anchor tag表示,假设我当前的网页网址为QueryString 当前广告

href

编辑后

xyz?x=2&y=4

我试过了。

HTML:

href="local/services"

的JavaScript

href="local/services?x=2&y=4"

也尝试了

<a href="http://localhost/services" onclick="appendString(this)">test link </a> 

但没有成功。 请提出解决方案。 感谢。

3 个答案:

答案 0 :(得分:2)

&#39; setAttribute&#39;的参数不正确。

  

element.setAttribute(name,value);

礼貌MDN:Element.setAttribute

答案 1 :(得分:1)

杰德伯克指出你的错误。所以你应该使用这样的东西:

function appendString(obj) {
    var url = obj.getAttribute('href');
    if (url.indexOf('?') != -1) obj.setAttribute('href', url + window.location.search);
}

甚至更简单:

function appendString(obj) {
    if (obj.href.indexOf('?') != -1) obj.href += window.location.search;
}

答案 2 :(得分:0)

您可以使用JQuery:

$('.myLink').click(function() {
$(this).attr("href", this.href + "?param=1");
});
相关问题