0

在此代码所在的表单中,每次单击 optionForm div 时都会触发微调器函数。第一次单击工作正常并触发一次警报。再次单击,它们会开火两次。第三次点击触发三次,等等。问题出在哪里?

<script type="text/javascript">

$("#optionForm").click(function() { 

    $("#process").hide().ajaxStart(function() {
        alert("show")
        $("#process").fadeIn('100');    
    })   
    .ajaxStop(function() {
        alert("hide")
        $("#process").hide();
    });

    $.post('post_requests.php', {

        scenario: ($('#scenario:checked').length ? 1 : 0 ),
        toolkit: ($('#toolkit:checked').length ? 1 : 0 ),
        newsletter: ($('#newsletter:checked').length ? 1 : 0 ),
        scenarios: $('#scenarios').val(),
        tools: $('#tools').val(),
        news: $('#news').val(),
        submit: 'yes'}, function(data) {

            $("#optionResponse").html(data).fadeIn('100');

            FadeMsg();

        }, 'text');

    function FadeMsg() {

        waiting = setInterval(function() {
            $('#optionResponse').fadeOut(500);
            },3000);    
    };

    clearInterval(waiting);
    return false; 

});         
</script>
4

3 回答 3

2

您应该将ajaxStartajaxStop调用放在点击处理程序之外。

如果将它们保留在单击处理程序中,则每次新的 ajax 请求开始或停止时都会添加一个新的回调。

该文档甚至有一个与您尝试执行的操作类似的示例:

每当 Ajax 请求开始时显示加载消息(并且没有一个处于活动状态)。

于 2012-04-16T13:35:42.467 回答
0

这可能是因为您每次单击 optionForm 时都订阅了一个函数。

试试这个。

$("#process").hide().ajaxStart(function() {
        alert("show")
        $("#process").fadeIn('100');    
    })   
    .ajaxStop(function() {
        alert("hide")
        $("#process").hide();
    });
$("#optionForm").click(function() { 
    // etc...
});
于 2012-04-16T13:38:21.320 回答
0

每次您单击optionFormdiv 时,都会触发 click 事件,并将新的 ajaxStart 事件附加到$("#process").
因此,当您第一次单击它时,会附加一个事件。
它工作正常。
下次您单击它时,将附加一个事件并触发两次。
. 相反,你应该附加ajaxStart()and 。ajaxStop()提前而不是在调用点击功能时发生事件

于 2012-04-16T13:39:40.407 回答