使用jquery使用window.location更改returnURL

时间:2012-08-15 10:21:12

标签: javascript jquery

我有以下链接:

<ul id="countrySelect">
<ul>
<li><a href="setlocale.aspx?returnURL=Default.aspx&amp;localesetting=en-US">EN</a></li>
</ul>

<ul>
<li><a href="setlocale.aspx?returnURL=Default.aspx&amp;localesetting=cs-CZ">CZ</a></li>
</ul>
<!-- END COUNTRY SELECT LIST -->
<p></p>
</ul>

我想从returnURL中删除Default.aspx,并将其替换为用户所在的当前页面。这是我试过的,但不确定它是否正确?

var pathname = window.location.pathname;
var countryArr = [];
var $ul = $('<ul id="countrySelect"/>');

countryArr = $('ul#countrySelect ul li a').map(function() {
        return this.value;
    }).get();

$.each(countryArr, function() {

$ul.append('<li>' + '<a href="setlocale.aspx?returnURL=' + pathname + '&localesetting=' + this.slice(0) + '">' + this.slice(3) + '</a>');

});

1 个答案:

答案 0 :(得分:1)

你能否这样做,基本上遍历每个<a>并在string.replace属性上执行href

$("a").each(function() {
    var oldHref = $(this).attr("href");

    var newHref = oldHref.replace("Default.aspx", window.location.pathname);

    $(this).attr("href", newHref);
});​​​

如果您的替换次数超过Default.aspx,这显然不起作用。您需要以下内容:

$("a").each(function() {
    var oldHref = $(this).attr("href");

    // get the URL to string.replace
    var toReplace = oldHref.substring(oldHref.indexOf("=") + 1, oldHref.indexOf("&"));

    var newHref = oldHref.replace(toReplace, window.location.pathname);

    $(this).attr("href", newHref);
});​​​