2012-11-15 41 views
10

我想創建一個Bootstrap警報框,記得用戶何時單擊關閉按鈕。我想我需要將這些信息存儲在cookie中。理想情況下,cookie只會持續當前會話,接下來他們將返回該框將再次出現。使用Bootstrap,有警示框記住關閉動作

我正在使用jQuery-Cookie插件。我把它上傳到/jquery-cookie-master。插件可以是found here

這是我到目前爲止通過以下代碼found here

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
<script src="/jquery-cookie-master/jquery.cookie.js"></script> 
<script> 
    function runOnLoad(){ 
     if($.cookie('alert-box') == null) { 
      $.cookie('alert-box', 'open', { expires: 7 }); 
     } else if($.cookie('alert-box') == 'close') { 
      $(".close").hide(); 
     } 

</script> 

HTML:

<body onload="runOnLoad()"> 

<div class="alert alert-info"> 
    <button type="button" class="close" data-dismiss="alert" href="hideMe.php" onclick="hideMe()">×</button> 
    <p> 
    <strong>FORUM UPGRADE:</strong> In light of our recent surge in popularity we upgraded our forum and unfortunately lost all the old threads in the process. 
    </p> 
    <p> 
    In an effort to kick-start the forum again we need your help. Sign up now and leave a post (it's free). Once we reach 100 threads every member will receive a special gift. 
    </p> 
    <p> 
    <a href="http://example.com/forum/#/entry/register"> 
     <strong>Sign up to the forum now</strong> 
    </a>. 
    </p> 
</div> 

</body> 

可惜這不是working.When我點擊關閉按鈕後不記得動作,如果我刷新頁面會再次出現警告框。

我做錯了什麼?

+0

燦有人幫忙嗎? – bennygill

回答

12

代碼問題

  • 在你的代碼你似乎是設置cookie的值,因爲你只需要設置cookie當用戶關閉警告框,這是奇怪的onload功能。

  • 您的按鈕有一個href屬性。這不是必需的,以及無效的HTML。

解決方案

爲了簡單地隱藏和記住你必須綁定一個事件關閉按鈕的警告框的狀態,讓你知道當用戶點擊關閉。

要綁定使用jQuery你可以使用下面的代碼的事件:

// When document is ready replaces the need for onload 
jQuery(function($){ 

    // Grab your button (based on your posted html) 
    $('.close').click(function(e){ 

     // Do not perform default action when button is clicked 
     e.preventDefault(); 

     /* If you just want the cookie for a session don't provide an expires 
     Set the path as root, so the cookie will be valid across the whole site */ 
     $.cookie('alert-box', 'closed', { path: '/' }); 

    }); 

}); 

要隱藏警告框,你應該簡單地檢查了正確的cookie值和隱藏對話框:

jQuery(function($){ 

    // Check if alert has been closed 
    if($.cookie('alert-box') === 'closed'){ 

     $('.alert').hide(); 

    } 

    // ... Binding code from above example 

}); 
+0

如何應用此多個div警報?可能與$這個,但不知道如何實現它。你有可能爲此添加小提琴嗎? – user2513846

+0

@ user2513846我建議將標識符添加到每個獨特的div警報。即alert-box-1 alert-box-2等 – hitautodestruct

+0

但是如何將它們添加到JS代碼中? (對不起,我沒有經驗的語法) – user2513846