我正在尝试创建一个Bootstrap警报框,记住用户单击关闭按钮的时间.我想我需要将这些信息存储在cookie中.理想情况下,cookie只会持续当前会话,然后他们返回该框将再次出现.
我正在使用jQuery-Cookie插件.我把它上传到了/jquery-cookie-master.插件可以在这里找到.
这是我到目前为止通过以下代码找到的.
<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>
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
不幸的是它没有用.当我点击关闭按钮时它不记得该动作,如果我刷新页面,警告框将再次出现.
我做错了什么?
hit*_*uct 15
在您的代码onload功能中,您似乎设置了奇怪的cookie值,因为您只想在用户关闭警报框时设置cookie.
您的按钮具有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: '/' });
});
});
Run Code Online (Sandbox Code Playgroud)
要隐藏警告框,您只需检查正确的cookie值并隐藏框:
jQuery(function( $ ){
// Check if alert has been closed
if( $.cookie('alert-box') === 'closed' ){
$('.alert').hide();
}
// ... Binding code from above example
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12561 次 |
| 最近记录: |