问题
I'm working on a jQuery predefined color picker. I'd like to save the color selection when the user click on one of the colors of my color picker: http://prntscr.com/7rnafa . To interact with cookies, I am using the jQuery plugin at https://github.com/carhartl/jquery-cookie .
jQuery code:
var color_elements_background = ".nodeList .categoryStrip, .breadcrumb";
var color_elements_text = "a:link, a:visited";
$(".colorPicker span").on("click", function()
{
var customColor = $(this).attr("custom_color");
$(color_elements_background).css("background-color", customColor);
$(color_elements_text).css("color", customColor);
});
});
HTML of my color picker:
<div class="colorPicker">
<div class="colorPickerContent">
<div class="colorPickerItems">
<li>
<span custom_color="#FF0000">Color 1</span>
</li>
<li>
<span custom_color="#333333">Color 2</span>
</li>
<li>
<span custom_color="#FFFFFF">Color 3</span>
</li>
<li>
<span custom_color="#D0D0D0">Color 4</span>
</li>
<li>
<span custom_color="#CCCCCC">Color 5</span>
</li>
</div>
</div>
</div>
回答1:
See the plugin:
https://github.com/js-cookie/js-cookie
To save a cookie using the Javascript library js.cookie you would use:
Cookies.set("color", customColor);
Also to get the value from the saved cookies would be:
var customColor = Cookies.get("color");
If you ever wanted to remove that cookie you would use:
Cookies.remove("color");
回答2:
Use the cookie library to store the previous selection, and populate the DOM using $( document ).ready(function(){}.
If your cookie is not saving, confirm the domain which the cookie is set. Often the cookie domain will not match your site when setting a cookie. Note that cookies will not save if you are using http://localhost. Use "Resources" tab within Chrome Dev tools to confirm your cookie is set.
p.s. If you want someone to do your work for you, consider freelancer.com or odesk.
来源:https://stackoverflow.com/questions/31369747/jquery-cookie-how-can-i-save-the-color-selection-of-the-user-for-the-next-visit