我有一个网址:
www.domain.com/bla/
结果页面中的按钮:
show 10, 20, 50 per page
和分页:
1, 2, 3, 5..
但是一旦我点击10
,网址就会变成www.domain.com/bla/?show=10
,然后如果我点击页面2
、show=10
正在消失并变成 www.domain.com/bla/?page=2
我有几个js解决方案,但是最好和最专业的方法是什么?
我的代码:
var show= $('#show').val();
var url = String(window.location);
if(url.indexOf("page") !== -1){
var newurl = url +'&show='+show;
$('.entries').html(' ').load(newurl, function(){
$(this).fadeIn();
});
}else{
var newurl = url +'?show='+sortterm;
$('.entries').html(' ').load(newurl, function(){
$(this).fadeIn();
});
}
最佳答案
只需使用JS replace
方法
var yourURL = "www.domain.com/bla/?page=10";
var newURL = yourURL.replace("?page", "?show"); //returns www.domain.com/bla/?show=10
更新:
借助此answer ,我学会了使用以下原型(prototype)在特定索引处插入字符串。
String.prototype.splice = function( idx, rem, s ) {
return (this.slice(0,idx) + s + this.slice(idx + Math.abs(rem)));
};
使用这个我修改了代码
var url = "www.domain.com/bla/?page=10";
var insertIndex = url.indexOf('page=10'); //get the index of page
var final = url.splice( insertIndex, 0, "page=2&" ).replace('&page', '&show');
console.log(final); //returns www.domain.com/bla/?page=2&show=10
关于javascript - js 并在加载前编辑 url - 如何执行此操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20242282/