Jquery+Javascript:使用toggle创建cookie

Jquery + Javascript : Creating a cookie with toggle

本文关键字:创建 cookie toggle 使用 Jquery+Javascript      更新时间:2023-09-26

我正在尝试创建一个cookie,所以如果:

一旦暴风雪效果停止并生成cookie,就会按下"切换",因此如果用户刷新页面,它将不会运行。如果他们再次"切换"它,暴风雪效应就会开始,cookie就会被删除。

此刻,我已经看了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;
}

所以我可以在伪代码中使用类似的东西:

$("#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() 

 });

有人能给我看一个点击时创建cookie,再次点击时删除cookie的例子吗?

我不知道该怎么做这一步。我想使用一个布尔变量并更改,当单击X时,X设置为true,如果再次单击,则X设置为false——然后我可以有一个删除或设置的方法。

为了更容易,您可以创建一次它,并切换其(而不是其existing)以打开/关闭雪。

你可以试试这个:

// 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";
    }
});

请参阅JSFiddle.net上的工作示例。