时间:2016-04-21 16:09:51

标签: javascript jquery html

我有以下代码,它突出显示(淡入/淡出)回复的注释(它是一个div元素)。

我在页面上只显示了10条最后评论 如果找到了评论,那么我突出显示它(工作正常),否则我加载所有评论然后尝试突出显示必要的评论。但是在else子句中的loadAllComments函数之后,hide()方法不起作用 - 我想知道为什么。

function showReply(reply){
var p = getElement(reply);

if (p) {
    $("#" + reply).animate({
        opacity: 0.5
    }, 200, function () {
    });
    setTimeout(function () {
        $("#" + reply).animate({
            opacity: 1
        }, 200, function () {
        });
    }, 1000);

}
else{
    loadAllComments(); //load all elements. working fine
    $("#"+reply).hide(); //nothing happens. :-(
}

function loadAllComments() {
    deleteComments();
    $('.show-more-button').hide();
    var xhr = new XMLHttpRequest();
    xhr.open('GET', api_url + 'video_comments/?video=' + video_id, true);
    xhr.withCredentials = true;
    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));


    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status != 200) {
                alert(xhr.responseText);
            }
            else {
                var comments = JSON.parse(xhr.responseText);
                for (var i = comments.results.length - 1 ; i >= 0 ; i--){
                    $('.comment-content-box').append(showComment(comments.results[i]));
                }
            }
        }
    };
    xhr.send();
}
function deleteComments(){
    var comments_count = $('.comment-content-box').children('div').length;
    for (var i=0; i < comments_count; i++){
        $('.comment-render-box').remove();
    }
}
function showComment(comment) {
    return "<div>" // example, there is plenty of code, but it's just a return function
}

1 个答案:

答案 0 :(得分:0)

您正在执行异步的XHR。在XHR完成后为loadAllComments提供一个回调函数:

function loadAllComments(callback) {
    deleteComments();
    $('.show-more-button').hide();
    var xhr = new XMLHttpRequest();
    xhr.open('GET', api_url + 'video_comments/?video=' + video_id, true);
    xhr.withCredentials = true;
    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));


    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status != 200) {
                alert(xhr.responseText);
            }
            else {
                var comments = JSON.parse(xhr.responseText);
                for (var i = comments.results.length - 1 ; i >= 0 ; i--){
                    $('.comment-content-box').append(showComment(comments.results[i]));
                }

                // xhr is complete and comments are now in DOM
                callback();
            }
        }
    };
    xhr.send();
}

...

// usage
loadAllComments(function() {
    $('#' + reply).hide();
});