JQuery:在页面加载时只执行一次淡入淡出

时间:2017-06-01 17:26:24

标签: javascript jquery

我有一些div我使用JQuery每隔10秒刷新一次这些div来检查更新的数据并显示它。所有这一切都很好用一个小例外。当页面首次加载时,它需要10秒钟才能显示某些div中的数据,因为定时器设置为10秒然后弹出。这看起来相当粗糙。所以我要做的是在第一次加载时淡入数据。我只是在页面首次加载时才需要它,否则它将每10秒钟淡出,这是我不想要的。我是JQuery的新手,并且找不到任何可以满足我要求的东西。那么如何在页面首次加载时仅淡入数据一次。

以下是我如何刷新数据的脚本示例。

function auto_load(){
        $.ajax({
          url: "inc/location_status.php",
          cache: false,
          success: function(data){
             $("#locationNotify").html(data);
          } 
        });
}

$(document).ready(function(){

auto_load(); //Call auto_load() function when DOM is Ready

});

//Refresh auto_load() function after 10000 milliseconds
setInterval(auto_load,10000);

然后例如在我想要数据出现的HTML中我只是做这样的事情。

<div id="locationNotify"></div>

修改

以下是我如何使其淡入的一个例子。这个方法的问题是每次div刷新/更新它都会淡入。我试图将它放在只有淡入一次的地方,那就是页面首次加载。是否有一个停止事件我可以添加,以便它只在页面加载时淡入一次,而不是每次脚本每10秒刷新/更新一次div。

function auto_load(){
        $.ajax({
          url: "inc/location_status.php",
          cache: false,
          success: function(data){
             $("#locationNotify").html(data).hide().delay().fadeIn(500);
          } 
        });
}

1 个答案:

答案 0 :(得分:0)

这应该能够帮助指导您达到您的目标。

&#13;
&#13;
/* Set Anonymous Function */
(function autoLoad(fadeIn) {
    /* Set Testing Post ID */
    var postId = Math.floor(Math.random() * 100);
    
    /* Call Ajax */
    $.ajax({
        url: '//jsonplaceholder.typicode.com/comments/' + postId,
        cache: false,
        success: function(data) {
            $('#locationNotify').html(data.name);
            if(fadeIn) {
                $('#locationNotify').hide().delay().fadeIn(500);
            }
        }
    });
    
    /* Set Tiemout */
    setTimeout(function() {
        autoLoad(false);
    }, 10 * 1000);
}(true));
&#13;
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="locationNotify" class="alert alert-danger text-center" style="display:none"></div>
&#13;
&#13;
&#13;

相关问题