【问题标题】:Edit URL before redirect重定向前修改 URL
【发布时间】:2014-03-20 10:12:16
【问题描述】:

在这里,我遇到了一个场景,我想在重定向之前编辑 hrefanchor tag。我的情况是,如果anchor taghref 属性不包含QueryString,则将上一页查询字符串附加到href 意味着,假设我当前的页面url 是xyz?x=2&y=4 当前的href

href="local/services"

编辑后

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

我试过了。

HTML:

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

JavaScript

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

也试过

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

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

【问题讨论】:

    标签: javascript html query-string


    【解决方案1】:

    “setAttribute”的参数不正确。

    element.setAttribute(name, value);

    感谢 MDN:Element.setAttribute

    【讨论】:

    • obj.setAttribute("href", url + window.location.search); 仍然重定向到没有 QS 的页面
    【解决方案2】:

    Jed Burke 指出了你的错误。所以你应该使用这样的东西:

    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;
    }
    

    【讨论】:

    • 你确定obj.href里面有?吗?
    • 那么应该是if (url.indexOf('?') == -1)
    • 哈,是的,新鲜的眼睛有时会有所帮助。
    【解决方案3】:

    您可以为此使用 JQuery:

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

    【讨论】:

    • 1.我要求Java Script 2。对不起,因为某些原因我不能使用类。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    • 2018-09-14
    • 2021-04-27
    • 2017-01-02
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多