简体   繁体   English

如何使用jQuery使div可见?

[英]how to make div visible using jquery?

 function showwaitmsg() {
        $("#wait").fadeIn();
        return  true;
    }
    function hidewaitmsg() {
        $("#wait").fadeOut();

    }

    $("a:contains('Test1')").bind("click", function () {
      if (showwaitmsg())
        test2(); // Function contains XMLHttpRequest
        hidewaitmsg();
    });


   <div id="wait" class="overlay" style="display: none">
             Please Wait
        <img src="~/loading.gif" />
    </div>

I am trying to show a "please wait" message using the above code while the XMLHttpRequest is being processed. 我正在尝试在处理XMLHttpRequest时使用以上代码显示“请稍候”消息。 The wait div is showing up too late after the request has been processed. 处理请求后,wait div出现太晚。 Can you please tell me what I should do to make the wait div visible as soon as the test1 button is clicked? 您能告诉我单击test1按钮后如何使wait div可见吗?

$("#id_of_button").on('click', function() {
    $("#wait").show();
});

Instead of calling showwaitmsg() and hidewaitmsg() outside of test2() , you should include them inside your ajax call. 与其在test2()之外调用showwaitmsg()showwaitmsg()hidewaitmsg()将它们包括在ajax调用中。

$.ajax({
    ...,
    beforeSend: showwaitmsg(),
    ...,
    complete: hidewaitmsg()
});

Returning false in the beforeSend function will cancel the request. beforeSend函数中返回false将取消请求。 As of jQuery 1.5, the beforeSend option will be called regardless of the type of request. 从jQuery 1.5开始,无论请求的类型如何,都会调用beforeSend选项。 It is also worth noting that complete is called after success and error callbacks are executed. 还值得注意的是,在success执行并回调error后将调用complete

It is much better to move this code to the AJAX call itself, like this: 最好将此代码移到AJAX调用本身,如下所示:

$.ajax({ 
    ...,
    beforeSend: function() {
        $('#wait').fadeIn();
    },
    complete: function() {
        $('#wait').fadeOut();
    }
});

It will help to separate the logic correctly and support more ways to make such AJAX call in your code, eg pressing keyboard button, etc. 这将有助于正确地分离逻辑,并支持在代码中进行此类AJAX调用的更多方法,例如,按下键盘按钮等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM