如何通过点击按钮覆盖Javascript中的Cookie值?

时间:2018-08-06 19:17:55

标签: javascript button cookies onclick overwrite

当用户单击按钮并使用Javascript时,我试图覆盖Cookie值。我想用onclick按钮中的新值替换默认的cookie值。我尝试在此处遵循该教程:https://www.quirksmode.org/js/cookies.html,但实际上并没有涉及有关实际按钮/超链接功能的详细信息。看起来他仅使用createCookie函数就能够更新/覆盖cookie,但是无论我如何尝试都行不通。这是我的代码如下:

<script>

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    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,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}


document.cookie = "sbhlocation_city=Muncie";
document.cookie = "sbhlocation_state=IN";


var setLocationCity = document.cookie.replace(/(?:(?:^|.*;\s*)sbhlocation_city\s*\=\s*([^;]*).*$)|^.*$/, "$1");
var setLocationState = document.cookie.replace(/(?:(?:^|.*;\s*)sbhlocation_state\s*\=\s*([^;]*).*$)|^.*$/, "$1");


</script>

<p class="body-text">
<script>
document.write(setLocationCity);
</script>
</p>

<p class="body-text">
<script>
document.write(setLocationState);
</script>
</p>

<button onclick="createCookie('sbhlocation_city','Waco',365)" href="#">Set City to Waco</button>

“城市”的默认cookie值应为Muncie,但是onlick按钮需要将“城市”的cookie值更改为Waco。当我尝试时,城市不会更新。我是Java的新手,因此非常感谢您的帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

尝试对此代码进行更正:

<button onclick="createCookie('sbhlocation_city','Waco',365)" href="#">Set City to Waco</button>

问题是“ sbhlocation_city”不是变量,是文本。 “ Waco”也是如此。 没有“ thisthingsaroundme”,它被当作变量名。因此会引发“未定义”错误。