基于Cookie值隐藏和显示内容 [英] Hide and Show content based on Cookie value
问题描述
这是我的Jquery:
$(#tool $(。chelp)。slideToggle();
$(wrapper)animate({opacity:1.0},200).slideToggle(200,function(){
$ tool img)。toggle();
});
});
当您点击 #tool img
#wrapper
与 .chelp
一起隐藏。
我需要使用Cookie控制此操作,因此,当用户隐藏#wrapper时,它会保留在所有网页或重新访问网页时隐藏。
我知道有一个jQuery Cookie插件,但我想使用纯JavaScript,而不是包括另一个插件。
任何人都可以告诉我我可以在纯javascript中构建它,并与JQuery合并创建一个cookie,然后检查cookie每次加载页面以查看是否应该隐藏或显示#wrapper。
Cookie扩展足够轻松,您不必创建一个新文件 - 只需将其插入到您的主要javascript文件。我已经这样做,它的工作正常。
要使用纯JavaScript和重新整合它与jQuery本质上将使用一个插件。 (看看Cookie的短原始代码是一个很好的方式来看看如何编写自己的插件,事实上。)
更新 / p>
这里有一些基本的jQuery可以用来测试和设置cookie。
if($ .cookie(hide-alert)==true){
$(#legal-alert)。
}
$(#legal-alert)。append(< div class ='close-alert'title ='Close'> x< / div>);
$(close-alert)。live(click,function(){
$(this).parent(。alert)。slideUp();
$ .cookie(hide-alert,true,{expires:365});
});
您需要的所有文档都在插件中(为了使其足够小直接放入我的js文件)。显然,你可以改变expires等。注意,上面的代码设置了一个按钮来关闭/隐藏框,然后为onClick设置一个现场监听器,这就是隐藏你想隐藏的框(我在上面称为#legal-alert)。
Here is my Jquery:
$("#tool").click(function() {
$(".chelp").slideToggle();
$("wrapper").animate({ opacity: 1.0 },200).slideToggle(200, function() {
$("#tool img").toggle();
});
});
When you click #tool img
#wrapper
is hidden along with .chelp
.
I need to control this with a cookie, so when the user hides #wrapper it remains hidden on all pages or when they re-visit the page.
I know there is a jQuery Cookie plugin, but I'd like to do this with plain Javascript rather then including another plugin.
Can anyone tell me how i can build in it in plain javascript and merge with the JQuery to create a cookie, then check the cookie each time the page loads to see if #wrapper should be hidden or displayed?
The Cookie extension is light enough that you don't have to create a new file--just insert it into your main javascript file. I've done so and it works just fine.
To use plain javascript and reintegrate it with jQuery would essentially be to use a plugin anyway. (Taking a look at Cookie's short raw code is a good way to see how to write your own plugin, in fact.)
Update
Here's some basic jQuery you can use to test for and set the cookie.
if ( $.cookie("hide-alert") == "true" ) {
$("#legal-alert").hide();
}
$("#legal-alert").append("<div class='close-alert' title='Close'>x</div>");
$(".close-alert").live("click", function() {
$(this).parent(".alert").slideUp();
$.cookie("hide-alert", "true", { expires: 365 });
});
All the documentation you need is in the plugin itself (which I deleted in order to make it small enough to put into my js file directly). Obviously, you can change 'expires' and such. Note that the above code sets a button to close/hide the box, and then sets a live listener for onClick, which is what hides the box you want to hide (I called it '#legal-alert' above).
这篇关于基于Cookie值隐藏和显示内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!