如何在html元素为空时加载gif并在非空时删除?

时间:2013-07-22 14:53:15

标签: jquery ajax loading

我有一个非常简单的搜索,我想在搜索时加载时获取加载图像。

<div id="search-filters">
    <button class="search">Search</button>
</div>
<div id="loading"></div>
<div id="results"></div>

我只有当#search s为空时点击div#result按钮才能获取加载图片,然后当div#results有一些内容隐藏#loading时。

这就是我所做的:

       $("#search").click(function() {
            if($.trim($("#results").html())=='') {
                $('#loading').show();
            }
            else if ($('#results:not(:empty)').length) {    
                $('#loading').hide();
            }
        });

但问题是,在我得到结果之后#loading不.hide(),为什么?
哪里出错了?
谢谢你的帮助!

2 个答案:

答案 0 :(得分:2)

我猜测ajax或类似的东西用于搜索,你必须等待它完成:

$("#search").on('click', function() {
    $('#loading').toggle( $("#results").is(':empty') );

    $.ajax({
        url : 'search.php', 
        data: this.value
    }).done(function(data) {
        $('#results').html(data);
    }).always(function() {
        $('#loading').hide();
        if ( $("#results").is(':empty') ) $('#results').html('No results !');
    });
});

答案 1 :(得分:0)

您不需要else if条件

试试这个 -

$("#search").click(function() {
            if($.trim($("#results").html())=='') {
                $('#loading').show();
            }
            else{    
                $('#loading').hide();
            }
});