2

我有一個網頁,只有註冊用戶可以。
我使用Bootstrap作爲CSS框架。
如果登錄用戶會有用這樣的successmessage一個警告框:如何用jquery只運行一次函數?

<div class="container"> 
    <div class="alert alert-success" role="alert"> 
     <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> 
     <strong>Success!</strong> You have been signed in successfully! 
    </div> 
</div> 

現在我想了幾秒鐘後關閉此。我用這個jQuery腳本來做到這一點:

window.setTimeout(function() { 
    $(".alert").fadeTo(500, 0).slideUp(500, function(){ 
    $(this).remove(); 
    }); 
}, 1500); 

我怎樣才能運行此代碼只有一次,所以如果用戶無意中刷新瀏覽器不會再看到這個警示?

我在這裏https://stackoverflow.com/a/23859937/5930557 閱讀這篇文章,知道它可以與.one()功能從http://api.jquery.com/one/
做,但我不知道如何把它列入到我的代碼。是否有人誰可以糾正它併爲我解釋,導致jquery和javascript是我的新手:P

+0

隨着刷新瀏覽器中的一個()函數將不會幫助你,你可以嘗試在localStorage的設置變量,用某種類型的會話ID進行檢查。 – JohannesB

+0

如果用戶刷新頁面,腳本將被重新加載,所以one()將不起作用。我會使用cookie或會話來做到這一點。如果會話或cookie存在,我將不運行腳本,否則它將運行。 – Pierre

+0

cookies或localStorage,或者只是調用顯示登錄成功函數警報的函數。 – Brian

回答

1

.one()將觸發一個事件一次,每次頁面加載所以不會爲你的榜樣工作。

作爲另一個答案說,你可以使用cookie,這樣的事情:

// get the cookie if its there 
var popUpShown = getCookie('popUpShown'); 
var numberOfDaysCookieExpiresIn = 99999999999; 

// check the cookie to see if the popup has been shown already 
if (popUpShown != '1') { 
    window.setTimeout(function() { 
    $(".alert").fadeTo(500, 0).slideUp(500, function(){ 
     $(this).remove(); 
    }); 
    }, 1500); 

    // set the cookie so we dont show the pop up again 
    setCookie('popUpShown', '1', numberOfDaysCookieExpiresIn); 
}; 
2

您可以使用cookie。它是解釋here

當頁面加載時,你可以檢查cookie,如果它是空的警報,如果它不是空的,你可以做你想做的事情。

1

解決方法是使用cookie並將其日期設置爲將來很遠。

注意:這個小提琴不允許你設置cookie。

$(function(){ 
 
    var popup = getCookie(popup); 
 
    if(popup){ 
 
//Dislay your alert 
 
     $('.container').append(
 
      ' <div class="alert alert-success" role="alert"> ' 
 
      + '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' 
 
      + '<strong>Success!</strong> You have been signed in successfully! </div>' 
 
     ); 
 

 
    } 
 
}); 
 

 
window.setTimeout(function() { 
 
    $(".alert").fadeTo(500, 0).slideUp(500, function(){ 
 
     $(this).remove(); 
 
     //Set the alert cookie to false 
 
     document.cookie = "popup=false; expires=Thu, 18 Dec 2090 12:00:00 UTC"; 
 
    }); 
 
}, 1500); 
 

 

 
//Function to get cookies 
 
function getCookie(cname) { 
 
    var name = cname + "="; 
 
    var ca = document.cookie.split(';'); 
 
    for(var i = 0; i <ca.length; i++) { 
 
     var c = ca[i]; 
 
     while (c.charAt(0)==' ') { 
 
      c = c.substring(1); 
 
     } 
 
     if (c.indexOf(name) == 0) { 
 
      return c.substring(name.length,c.length); 
 
     } 
 
    } 
 
    return ""; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="container"> 
 
    
 
</div>