仅当用户单击复选框时才记住我的Cookie

时间:2018-11-05 15:56:40

标签: javascript html

更新的代码:感谢您到目前为止的建议。仍然无法正常工作。

我试图添加一个记住我的cookie,但仅当用户实际单击该复选框时才添加。这可能吗?我没有这个代码的运气。无论是否选中该复选框,都会触发Cookie:

JavaScript:
    <script>  
        $('#rememberme').click(function() {

        if ($('#rememberme').is(':checked')) {
            document.cookie="rememberme=yes;domain=.abc.com;path=/"
        localStorage.usrname = $('#username').val();
            localStorage.pass = $('#password').val(); localStorage.chkbx = $('#rememberme').val();
        } 
    else {
            document.cookie="rememberme=no;domain=.abc.com;path=/"
            localStorage.usrname = '';
        localStorage.pass = '';
        localStorage.chkbx = '';
    }
    });
</script>

HTML:
<label class="checkbox" style="border: none;">
    <input type="checkbox" value="rememberme" id="rememberme"> Remember me
</label>

3 个答案:

答案 0 :(得分:0)

更新代码

$('#rememberme').click(function() {
    if ($('#rememberme').is(':checked')){

  document.cookie = "rememberme=yes;domain=.abc.com;path=/"
  // save username and password
  localStorage.usrname = $('#username').val(); localStorage.pass = $('#pass').val(); localStorage.chkbx = $('#rememberme').val();
}
else {
  document.cookie = "rememberme=no;domain=.abc.com;path=/"
  localStorage.usrname = '';
  localStorage.pass = '';
  localStorage.chkbx = '';
}
});

答案 1 :(得分:0)

在jsfiddle中的代码下面进行了测试,希望它可以根据您的需要工作。请对其进行一次测试,让我知道它是否按预期工作。

https://jsfiddle.net/arivua/xpvt214o/924480/

// set cookie value
function setCookie(key, value) {
  document.cookie = key +"="+ escape(value) +
    ";domain="+ window.location.hostname +
    ";path=/";
}
// delete cookie
function deleteCookie(name) {
  setCookie(name, "");
}

var remember_me_check_box = $("#rememberme")
// handle click and manage cookie
remember_me_check_box.on("click", function(){
  if (remember_me_check_box.is(':checked')) {
    deleteCookie('rememberme');
    setCookie('rememberme', 'yes');
  } else {
    deleteCookie('rememberme');
    setCookie('rememberme', 'no');
  }
})

答案 2 :(得分:0)

解决方案是仅在声明记忆的URL周围设置“ If”和“ else”条件。但是,条件URL的构造(注意是vs否)是由我是前端UI开发人员的后端人员处理的。

<script>  
    $('#rememberme').click(function() {

    if ($('#rememberme').is(':checked')) {
        document.cookie="rememberme=yes;domain=.abc.com;path=/";
    } 
else {
        document.cookie="rememberme=no;domain=.abc.com;path=/";
    }
});