可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have an idea how to implement this, but it doesn't seem that of all the similar posts, anybody is able to give a simple example. I want to simply store the value of the toggle state of "marketing-message-global" in a cookie. If the user clicks "hide-marketing-message-btn", the toggled state will be stored in a cookie. When the user refreshes the page, the stored toggle state will be used, and hide the div that was toggled off.
<div id="marketing-message-global"> </div> <div id="hide-marketing-message-btn"> </div> $(document).ready(function() { if $('#hide-marketing-message-btn").clicked() { $("#marketing-message-global").hide(); $.cookie("toggle-state") == true; } if ($.cookie("toggle-state") == true) { $("#marketing-message-global").hide(); } else if ($.cookie("toggle-state") == false) { $("#marketing-message-global").show(); } }); </script>
回答1:
I used jquery cookie plugin (https://github.com/carhartl/jquery-cookie)
$(function(){ if($.cookie){ //By default, if no cookie, just display. $("#marketing-message-global").toggle(!(!!$.cookie("toggle-state")) || $.cookie("toggle-state") === 'true'); } $('#hide-marketing-message-btn').on('click', function(){ $("#marketing-message-global").toggle(); //Save the value to the cookie for 1 day; and cookie domain is whole site, if ignore "path", it will save this cookie for current page only; $.cookie("toggle-state", $("#marketing-message-global").is(':visible'), {expires: 1, path:'/'}); }); });
回答2:
I think this should work:
1) If you want to set the cookie by some events else:
$(document).ready(function() { if ($("#hide-marketing-message-btn").prop("hidden") == "hidden") { $("#marketing-message-global").hide(); $.cookie("toggle-state") == true; } else { // ... } });
2) Setting cookie by clicking on div and performing toggle at once:
$(document).ready(function() { $("#hide-marketing-message-btn").click(function() { if ($("#hide-marketing-message-btn").prop("hidden") == "hidden") { $("#marketing-message-global").hide(); $.cookie("toggle-state") == true; } else { // ... } }); });