2012-08-15 32 views
0

window.location的,我有以下链接:变化RETURNURL与使用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

你能不能做到这一点,基本上是通过每个迭代<a>并在href属性做了string.replace

$("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); 
});​​​ 
+0

我想这会更简单! – 2012-08-15 10:28:08

+0

@ Super2更新,使其更适合实际使用。 – 2012-08-15 10:31:17

+0

它不改变returnURL,即使我添加了这一行:'$(“ul#countrySelect ul li a”)。each(function(){' – 2012-08-15 10:32:53