1
    $.ajax({
        type:'POST',
        dataType:'json',
        data:{ },
        url:'pulldata.php',
        timeout:3000,
        success:function (data) {

            $('#thediv').html(data.html);

            $(".expandhide").click(function () { // THIS IS WHERE I'M STUCK
                $(this).parents().next(".infopanel").toggle(500);
            });


            window.setTimeout(update, 3000);
        },
        error:function (XMLHttpRequest, textStatus, errorThrown) {
            window.setTimeout(update, 60000);
        }
    });

.expandhide 函数展开/隐藏元素。我需要 ajax 在用户单击 .expandhide (扩展)时停止进一步调用,并在用户再次单击它时恢复 ajax 调用(以隐藏它)。几乎完全是我如何切换 .infopanel,除了使用 ajax 来停止/继续调用。这可以做到吗?

4

1 回答 1

2

将间隔设置为变量并在隐藏时将其清除:

var timeout = null;
var expanded = false;
var ajax = null;
$(".expandhide").click(function() {
    expanded = !expanded; //Reverse it
    if (expanded) {
        update(); //Call update again but right away
    } else {
        //Abort the ongoing ajax call (if any)
        if (ajax !== null) ajax.abort(); 

        //Clear the timeout
        if (timeout !== null) clearTimeout(timeout); 
    }
});

//Set the global "ajax" variable to our request - don't use "var" here
ajax = $.ajax(
    ...
    success: function(data) {
        // Do NOT use "var" here, as we're referencing the global variable
        timeout = setTimeout(update, 3000);  
    }
    ...
);

或者,作为快速修复,只需添加一个beforeSend匿名函数,如果您.infopanel不可见,则取消发送它:

$.ajax(
    ...
    beforeSend: function(jqXHR, settings) {
        if ($(".infopanel").is(":hidden")) {
            return false; //Don't send the request
        }
    }
);
于 2013-08-12T16:48:08.753 回答