【问题标题】:jquery .load function running more than oncejquery .load 函数运行不止一次
【发布时间】:2019-07-08 04:03:49
【问题描述】:

我正在尝试按照此处 (http://scrollsample.appspot.com/items?page=7) 中看到的 google 建议实现 SEO 友好的无限滚动。我有一个 jquery 函数,它向 php 文件发送请求,(它从 db 请求数据)只要有人滚动到页面底部,现在一切正常,除了当用户滚动到页面底部时,请求函数被触发不止一次。所以重复的数据条目被加载到页面中,现在我知道这不是来自我的 php 文件,因为我直接在浏览器中打开了页面,一切都很好。在这里检查错误http://devx.dx.am/haze/categor.php?artemis=foo&&page=1

我已经尝试过这里 (jQuery .load() callback function fires multiple times) 和这里 ($(window).load() is executing 2 times?) 以及其他一些解决方案。

$(window).bind('scroll', function() { //#cagorwrap is the div that should contain the data retrieved
    if($(window).scrollTop() >= $('#cagorwrap').offset().top + $('#cagorwrap').outerHeight() - window.innerHeight) { //344.6
      var queryParameters = {}, queryString = location.search.substring(1),
      re = /([^&=]+)=([^&]*)/g, m;
      while (m = re.exec(queryString)) {
          queryParameters[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
      }
      var url2 = "modules/paginate.php?numpages=set";
 // #rc is a hidden div too
      $("#rc").load(url2, function() {
        var rc = $(this).html();
        if (queryParameters['page'] < rc) {
          queryParameters['page']++;
          console.log(rc);
          var stateObj = queryParameters['page'];
          let cagh = $('#cagorwrap').height() + 344.6 - 75;
          $("#cagorwrap").height(cagh);
          history.pushState(null, null, "categor.php?artemis=cat&&page="+stateObj);
          var url = "modules/paginate.php?artemis=cats&&page="+stateObj;
          $("#obtainer").load(url, function () {
            $("#cagorwrap").append($(this).html());
          }); //#obtainer is a hidden div that receives the data at first before it is appended to #cagorwrap
        } else{
          //unbind scroll here
        }
      });
    }
});

【问题讨论】:

  • 您在“滚动”回调中调用 $("#rc").load(url2, function() { 等。这意味着每次调用滚动事件处理程序时,您都会添加一个新的load 事件处理程序。这就是它多次发射的原因。
  • 好的,这指出了一些工作,我起初怀疑这一点,但忽略了......它现在正在工作。嫁给我:)

标签: php jquery ajax


【解决方案1】:

好吧,如果所有其他方法都失败并且您绝对需要解决方案,您可以添加一个 counter=1; 开始 并且仅在以下情况下触发请求功能

  counter++;
    if (counter%2==0){//fire request}

它不干净,但是如果您为此浪费了太多时间并且想稍后再回到这个问题......

【讨论】:

    猜你喜欢
    • 2011-11-27
    • 2015-09-21
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-15
    • 1970-01-01
    相关资源
    最近更新 更多