加载后隐藏旋转器

Hide spinner after loading

本文关键字:旋转 隐藏 加载      更新时间:2023-09-26

我想在加载页面后隐藏旋转器我试过了:

$(document).ready(function() {
$('.loader')
    .hide()  // Hide it initially
    .ajaxStart(function() {
        $(this).show();
    })
    .ajaxStop(function() {
        $(this).hide();
    });
 });

还有这个div:

<style>
.loader {
    position: fixed;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
    z-index: 9999;
    background: url("{{ asset('img/loading.gif') }}" )  50% 50% no-repeat rgb(249,249,249);
}
</style>
    <div class="loader"></div>

但是没有结果

您可以通过使用.ajaxSend().ajaxComplete() Ajax事件来实现这一点处理程序

  1. . ajaxsend ():每当Ajax请求即将被发送时,jQuery触发ajaxSend事件。任何和所有已经注册到.ajaxSend()方法的处理程序都将在此时执行。
  2. . ajaxcomplete ():每当Ajax请求完成时,jQuery触发ajaxComplete事件。所有已经注册.ajaxComplete()方法的处理程序都将在此时执行。

我使用下面的代码来显示ajax请求时的加载器,然后在ajax请求完成后隐藏它。

代码如下:

var ajax_req_no = 0;
(function ($) {
$(document).ajaxSend(function () {
        ajax_req_no = (ajax_req_no < 0) ? 0 : ajax_req_no;
        ajax_req_no++;
        if ($('.loader').length) {
            $('.loader').show();
        }
    });
    $(document).ajaxComplete(function () {
        ajax_req_no--;
        ajax_req_no = (ajax_req_no < 0) ? 0 : ajax_req_no;
        if ($('.loader').length && ajax_req_no == 0) {
            $('.loader').fadeOut();
        }
    });
})(jQuery);

由于ajax请求可以嵌套,所以ajax_req_no是计算请求的数量,如果计数多于一个loder将显示,否则loder将被隐藏。

注意:从jQuery 1.8版本开始,这个方法应该只附属于document


参考:

  • .ajaxSend ()
  • .ajaxComplete ()

您是否能够在ajax调用之前的代码中放置.show(),然后在.success().done()中放置.hide()

$("#buttonStartingAjax").click(function(){
    $(".loader").show();
    $.ajax({...}).done(function(){
        $(".loader").hide();
        ...
    });
)};

我觉得你在找这样的东西:

$(document).ready(function() {
  $(document)
    .ajaxStart(function() {
      console.log('some AJAX request has started'); 
      $(".loader").show();
    })
    .ajaxStop(function() {
      console.log('all AJAX requests have completed'); 
      $(".loader").hide();
    })
  ;
  $("#btn").click(function() {
    // trigger some AJAX call
    $.get('example.com');
  });
});
.loader {
  position: fixed;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  /*z-index: 9999;*/ /* to see demo's console.log */
  background: url("img/loading.gif")  50% 50% no-repeat yellow;
  display: none; /* unless overriden by jQuery */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="loader"></div>
<button id="btn">Trigger an AJAX request</button>