jQuery脚本发射两次?也许现场活动正在开火两次



我正在使用最新版本的PhoneGap,JQM和JQuery 1.8.0构建应用程序。到目前为止,除了我遇到的这个小小的烦人的问题外,一切都很好。

我从index.html链接了我的show.html,其中包含以下代码:

<div id="search"> contains search bar and submit button </div>
<div id="list" style="display:none;"> 
      <ul data-role="listview" data-filter="true"> </ul>
</div>

UL标签为空,因为当单击"提交"按钮时,将使用AJAX动态地附加列表。我不想首先显示#List Div,所以我将显示设置为无。

这样可以正常工作,当单击"提交"按钮时,它将向服务器发送AJAX请求并将项目附加到列表中。它也将隐藏搜索部门。这也可以!

现在问题出现了,我添加了一个窗口。Croll功能以检测何时到达页面的底部。

这是我的jQuery代码:

$(document).on("pageshow", "#pageID", function() {
    $("#submit").click(function() {
        $.ajax({
                success: function(data, status){
                  $('#search').hide();
                  $('#list').show();
                //append to list div and refresh list here
                }
        });
    });
    //detects bottom of page
    $(window).scroll(function () {
        if ($(window).scrollTop()+200 >= ($(document).height() - ($(window).height()))) {       
            console.log('end of the page');
                        lastPostFunc(); //infinite scroll function
        } 
    });  
});

这是页面的末端两次,到了firebug控制台!此脚本存在于Head Tag之间。

无论如何是否有一次打印一次?我之所以需要这个,是因为我实现了自己的无尽的滚动功能,问题导致我的Ajax请求将两次发布到服务器。该功能效果很好,但不是出现问题的原因,因为即使我评论了LastPostFunc(),它仍然两次打印到控制台!

编辑:就我个人而言,我认为给出的答案不是错误的,它们是正确的,但它们没有帮助我解决问题。也许我需要更好地改善事物。我复制了我的代码并将其粘贴到独立页面上,它仅打印一次,因此我的代码实际上没有错,它的工作原理。

因此,我想知道是否还有其他原因在提交表格后两次打印。我的表单和结果页面是同一页面上的。这是否意味着这导致现场活动两次工作?因此,使其在页面上两次将其打印到控制台?如果我是正确的,那么无论如何是否可以解决此问题,并使它仅打印曾经

任何帮助将不胜感激。谢谢!

好吧,我终于解决了。

显然我要做的就是将此代码添加到其中:

    $(window).scroll(function (e) {
        if (reach bottom) {
            e.stopImmediatePropagation();
            console.log('End of the Page');
        } 
    });

它有效!为我停止打印两次。

您的功能实际上将输出输出两次以上。问题在于您的状况:

if ($(window).scrollTop()+200 >= ($(document).height() - ($(window).height())))  

因为对于此区域内的每一个滚动条件,条件都会对真实进行评估。您可以将其更改为:

if ($(window).scrollTop() == ($(document).height() - ($(window).height())))

可能会解决您的问题

jQuery(window).scroll(function() {
    if( (jQuery(document).height() < (jQuery(window).scrollTop() + jQuery(window).height() + 200))&&(jQuery(document).height() > (jQuery(window).scrollTop() + jQuery(window).height() + 99))) {        
    console.log('test')                                         
    }
}); 

//更新

    var lastlogtime= null;
jQuery(window).scroll(function() {
        if( (jQuery(document).height() < (jQuery(window).scrollTop() + jQuery(window).height() + 200))&&(jQuery(document).height() > (jQuery(window).scrollTop() + jQuery(window).height() + 99))) {
        if(((lastlogtime+600)<(+new Date())) || (lastlogtime== null)){
            //your scroll logic
            console.log('test')         ;
            lastlogtime=    +new Date();                            
            }
        }
    });

最新更新