JS-为什么这不起作用-任何错误

JS - why is this not working - any bug?

本文关键字:任何 错误 不起作用 为什么 JS-      更新时间:2023-11-04

我有这样的代码,它将page=value搜索参数添加到url并加载页面。但这不起作用,它没有设置网址,我有任何打字错误吗?

$(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>

浏览器正在跟踪链接的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;
          }
        });
  });