jQuery没有正确隐藏/显示元素

时间:2015-06-23 21:04:48

标签: javascript jquery html css

我的网页模板中有以下html和jQuery代码。

$ .getJSON调用可能需要一些时间,因此我想在加载数据时显示警告(div为id =“warning”),以便用户知道等待它。

代码正确验证状态下拉列表,并返回表格的正确数据,表格显示正常。

但是,单击提交按钮时,警告段落不会显示,并且在加载数据时表仍然可见。

如何在加载数据时使表格消失并显示警告?

  <div class="container-fluid">
  <form id="search_form">
      <div class="container-fluid">
          <div class="row">
              <div class="col-xs-4">
                  {{ render_field(form.status) }}
              </div>
              <div class="col-xs-4">
                  <input type="submit" value="Get Issues" id="submit">
              </div>
              <div class="col-xs-4">
              </div>
          </div>
          <div class="row">
              <div hidden="true" id="warning" class="col-xs-12 center alert alert-warning">
              <p>Data is loading, this might take a few seconds</p>
              </div>
          </div>
          <div class="row">
              <div id="errors" hidden="true" class="col-xs-12 center alert alert-danger">
              </div>
          </div>
      </div>
  </form>

  <script>
  var table;
  $('#submit').click(function(event) {
      event.preventDefault();

      if (!$('#status').val()) {
          $('#errors').html('');
          $("<p>Please select a status</p>").appendTo($('#errors'));
          $("#errors").show();
          $("#table_div").hide();
          return;
      } else {
          $("#errors").hide();
      }

      $("#warning").show();
      //get the data for the table
      $.getJSON("/all_issues/status/" + $("#status").val(), function(data) {
          table = $('#search_table').dataTable( {
              destroy: true,
              "data": data,
          });
          $('#table_div').show();
      });
      $("#warning").hide();
  });

1 个答案:

答案 0 :(得分:1)

$("#warning").hide()回调中移动$.getJSON()

$.getJSON()是一个AJAX调用,因此回调是异步执行的。在您当前的设置中,您在显示它之后立即隐藏<div id="warning">,而在您加载JSON之后想要隐藏它。