如果cookie存在则设置天气位置,如果没有请求位置并将其保存在cookie中

时间:2012-12-13 14:24:43

标签: jquery cookies

//minimize latest news
window.document.querySelector("#ncWrapper > #nc > #action_ncMinMax").click();

//select location in weather
// $("a:contains('München')").click();

// check if variable is stored in cookie
var loc = $.cookie('loc_cookie');
if ( loc != null) {
    alert('loc existiert');
    var loc_exists = 1;
}
else { var loc_exists = 0; };

// only ask for location if no location is saved yet [functions inside if work]
if ( !loc_exists ) {
    var loc = prompt("Wählen Sie den Ort für den Wetterbericht?");
    alert('Sie haben ' + loc + ' als Ort für den Wetterbericht gewählt.');
};

    $("a:contains('" + loc + "')").click();

// save to cookie
$.cookie('loc_cookie', loc);
alert('loc in Cookie gespeichert');

任何人都可以帮助我吗? var loc = $.cookie('loc_cookie');似乎不起作用。我只是复制/粘贴它,希望你知道,我想让js做什么。

  1. 寻找Cookie - >获取cookie并保存(如果存在)
  2. 如果不存在,请询问位置||如果if什么都不做。
  3. 获取位置。
  4. 在Cookie中保存位置。

4 个答案:

答案 0 :(得分:3)

删除if / else块中的“var”关键字。通过添加它,您可以创建一个新的局部变量。

// check if variable is stored in cookie
var loc = $.cookie('loc_cookie');
if ( loc != null) {
    alert('loc existiert');
    var loc_exists = 1;                 <- new instance of loc_exists
}
else { var loc_exists = 0; };           <- new instance of loc_exists

应该是

// check if variable is stored in cookie
var loc = $.cookie('loc_cookie');
var loc_exists;
if ( loc != null) {
    alert('loc existiert');
    loc_exists = 1;
}
else { loc_exists = 0; };

最后,使用布尔值可能更清楚:

if ( loc != null) {
    alert('loc existiert');
    loc_exists = true;
}
else { loc_exists = false; };

答案 1 :(得分:1)

您需要在页面中包含jQuery Cookie插件才能使用$ .cookie。它默认不包含在jQuery中。

https://github.com/carhartl/jquery-cookie

答案 2 :(得分:0)

Johnny Mopp是对的。

您的问题是您已在loc_exists声明中声明了if

要解决此问题,请将声明移到外部,并在语句中设置其值:

var loc = $.cookie('loc_cookie');
var loc_exists = 0;
if ( loc != null) {
    alert('loc existiert');
    loc_exists = 1;
}

答案 3 :(得分:0)

这是我的代码。似乎工作得很好。不幸的是,die网站在此期间添加了该功能^ _ ^

// check if variable is stored in cookie
var loc = $.cookies.get('loc_cookie');
if ( loc != null) {
    alert('loc existiert');
    var loc_exists = 1;
}
else { var loc_exists = 0; };

// only ask for location if no location is saved yet [functions inside if work]
if ( !loc_exists ) {
    var loc = prompt("Wählen Sie den Ort für den Wetterbericht?");
    alert('Sie haben ' + loc + ' als Ort für den Wetterbericht gewählt.');
};

$("a:contains('" + loc + "')").click();

// save to cookie
$.cookies.set('loc_cookie', loc);
alert('loc in Cookie gespeichert');