我有这段代码,它会将page=value
搜索参数添加到网址并加载页面。但这不起作用,它没有设置网址,我有没有错字?
$(function(){
$('.page').on('click',function(){
var page = $(this).text();
var url = String(window.location);
var newurl = "";
if(url.indexOf("?") !== -1){
if(url.indexOf('page') !== -1){
newurl = url.replace(/([&?]page=)[^&]*/, "$1" + String(page));
window.location = newurl;
}else{
newurl = url +'&page='+String(page);
window.location = newurl;
}
}else{
newurl = url +'?page='+String(page);
window.location = newurl;
}
});
});
HTML
<a href="" class="page">1</a>
<a href="" class="page">2</a>
<a href="" class="page">3</a>
<a href="" class="page">4</a>
答案 0 :(得分:2)
浏览器正在关注链接的href。 使用preventDefault修复脚本。
$(function(){
$('.page').on('click',function(e){
e.preventDefault();
var page = $(this).text();
var url = String(window.location);
var newurl = "";
if(url.indexOf("?") !== -1){
if(url.indexOf('page') !== -1){
newurl = url.replace(/([&?]page=)[^&]*/, "$1" + String(page));
window.location = newurl;
}else{
newurl = url +'&page='+String(page);
window.location = newurl;
}
}else{
newurl = url +'?page='+String(page);
window.location = newurl;
}
});
});