【问题标题】:Eliminate Duplicate Entries消除重复条目
【发布时间】:2010-12-29 09:28:26
【问题描述】:

我正在使用以下 javascript 在父页面中动态加载外部页面的内容。外部页面与父页面在同一域内,并在数据库中查询博客条目。我正在使用变量“eeOffset”将一个值传递给外部页面中的数据库查询以抵消返回的结果,即如果 eeOffset 为“5”,则查询从第 6 个返回下一个数据库记录。 “eeLimit”变量设置每个请求返回的项目总数。我遇到的问题是父页面中显示的条目被重复 - 就好像模板页面的 url 在触发新项目的请求之前没有被更新。有人对如何克服这个问题有任何建议吗?

var eeLoading; // Declare variable "eeLoading"
var eeTemplate = "http://www.mydomain.com/new_items/query"; // URL to template page
var eeOffset; // Declare variable "eeOffset"
var eeLimit = "5"

//Execute the following functions when page loads
$(function (){
    scrollAlert();
    $("#footer").append("<div id='status'></div>"); //Add some html to contain the status and loading indicators
    updateStatus(); // Update the total number of items displayed
    });

//Update Status
function updateStatus(){
    var totalItems = $("ul.column li").length;
    eeOffset = totalItems;
    eeURL = eeTemplate+"/"+eeOffset+"/"+eeOrderby+"/"+eeSort+"/"+eeLimit+"/"; // Build the template page url
    }

//Scoll Alert 
function scrollAlert(){
    var scrollTop = $("#main").attr("scrollTop");
    var scrollHeight = $("#main").attr("scrollHeight");
    var windowHeight = $("#main").attr("clientHeight");
    if (scrollTop >= (scrollHeight-(windowHeight+scrollOffset)) && eeLoading !== "false"){
        $("#status").addClass("loading");
        $.get(eeURL, function(newitems){ //Fetch new items from the specified url
            if (newitems != ""){ //If newitems exist...
                $("ul.column").append(newitems); //...add them to the parent page
                updateStatus(); //Update the status
                }
            else {
                eeLoading = "false"; //If there are no new items...
                $("#status").removeClass("loading"); //Remove the loading throbber
                $("#status").addClass("finished");  //Add some text
                }
            });
        }
    if (eeLoading !== "false") { //If there are still new items...
        setTimeout("scrollAlert();", 1500); //..check the scollheight every 1500ms
        }
    }

【问题讨论】:

    标签: javascript jquery duplicates


    【解决方案1】:

    您的代码中似乎存在竞争条件。如果完成对新项目的请求超过 1.5 秒,您将在调用 updateStatus() 之前触发下一个请求。我认为解决此问题的最简单方法是移动此代码:

    if (eeLoading !== "false") { //If there are still new items...
        setTimeout("scrollAlert();", 1500); //..check the scollheight every 1500ms
        }
    

    在 if 语句中,在 updateStatus() 调用后更新要查询的 url:

    if (newitems != ""){ //If newitems exist...
       $("ul.column").append(newitems); //...add them to the parent page
       updateStatus(); //Update the status
       // Move setTimeout here
    

    这样,当您请求新网址时,状态将始终更新。

    【讨论】:

      猜你喜欢
      • 2013-04-24
      • 1970-01-01
      • 1970-01-01
      • 2021-01-22
      • 2016-05-22
      • 2014-08-01
      • 2013-03-09
      • 2013-07-12
      • 2018-10-16
      相关资源
      最近更新 更多