[英]Jquery + Javascript : Creating a cookie with toggle
I'm trying to create a cookie, so if: 我正在尝试创建一个cookie,因此:
"Toggle" is pressed once a snow storm effect will stop and also generate a cookie so if the user refreshes the page, it will not run. 一旦暴风雪效果将停止并且还会生成Cookie,则按下“切换”按钮,因此,如果用户刷新页面,它将不会运行。 And if they "Toggle" it again the snow storm effect will start and the cookie gets deleted.
如果他们再次“切换”,暴风雪效果将开始并且cookie被删除。
At the moment, i have looked at http://www.w3schools.com/js/js_cookies.asp and i need to use the following functions: 目前,我已经查看了http://www.w3schools.com/js/js_cookies.asp ,我需要使用以下功能:
document.cookie="name";
function get_cookie(name){
var x = name;
}
function delete_cookie( name ) {
document.cookie = name;
}
So i can have something like in pseudo code : 所以我可以在伪代码中有一些类似的东西:
$("#Snow").click(function () {
snowStorm.toggleSnow()
// Generate a cookie here and returns it //
// Selected again, cookie is deleted //
});
$(document).ready(function(){
$("#Winter").click(function(){
// Gets the cookie and doesn't run the snowStorm.resume
// If no cookie, runs it.
snowStorm.resume()
});
Could anyone please show me an example of creating a cookie when clicked and deleted when clicked again? 任何人都可以向我展示创建一个Cookie的示例,该示例在单击时创建,然后再次单击时删除。
I'm not sure how to do this step. 我不确定如何执行此步骤。 I thought of doing using a boolean variable and alter changing , when clicked X sets to true, if clicked again X is set to false - where i then can have a method for deleting or setting.
我想到要使用布尔变量并更改change,当单击X设置为true时,如果再次单击X设置为false,则可以在其中设置删除或设置方法。
To make it easier, you can create it once and toggle its value (rather than its existence ) to turn on/off the snow. 为了简化操作,您可以创建一次并切换其值 (而不是它的存在 )以打开/关闭积雪。
You can try this: 您可以尝试以下方法:
// this getCookie() function is copied from W3Schools
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
// initialization
var on = getCookie("snow");
if(on == "") {
document.cookie = "snow=true";
start();
} else {
(on == "true") ? start() : stop();
}
// toggling
$("#Winter").click(function() {
if(getCookie("snow") == "true") {
stop();
document.cookie = "snow=false"; // overwrite the cookies to change them
} else {
start();
document.cookie = "snow=true";
}
});
See the working example on JSFiddle.net. 请参阅JSFiddle.net上的工作示例 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.