2013-11-27 34 views
-2

我有這樣的代碼,這將增加page=value搜索參數的URL和加載頁面。但這不起作用,它不設置網址,我有任何錯字嗎?JS - 爲什麼這不起作用 - 任何錯誤?

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

什麼是不正確的工作? – adeneo

+0

@adeneo,正如我所說的,它沒有設置網址 – doniyor

+1

在發佈之前,您應該使用控制檯檢查拼寫錯誤/錯誤。 – lifetimes

回答

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; 

      } 
     }); 
    });