【问题标题】:JS - why is this not working - any bug?JS - 为什么这不起作用 - 任何错误?
【发布时间】:2013-11-27 16:53:15
【问题描述】:

我有这段代码,它将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>

【问题讨论】:

  • 什么不正确?
  • @adeneo,正如我所说,它没有设置 url
  • 您应该在发帖前使用控制台检查拼写错误/错误。
  • @DSG,我已经做到了。我没有看到任何错误,然后我在这里发布了
  • 您需要阻止默认操作发生$('.page').on('click',function(e){ e.preventDefault()。如果没有,默认操作(在这种情况下是页面重新加载)将发生。因此问题

标签: javascript django


【解决方案1】:

浏览器正在关注链接的 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;

          }
        });
  });

【讨论】:

    猜你喜欢
    • 2014-09-12
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    • 2012-11-17
    相关资源
    最近更新 更多