页面重新加载时更改文本

时间:2017-07-29 17:36:32

标签: javascript jquery cookies

我做了一个基本的表格,在你输入一个输入并提交cookies show" welcome" +名称

我添加了第二个Cookie,当您重新加载同一页面时,上面的文字会消失并说“欢迎回来”#34; +名字。

我是使用Cookie的新手,无法正常使用这些功能。

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <form>
        <input id="user" type="user" name="user">
        <input id = "submit" type="submit" name="submit">
    </form>
    <h1 id ="greeting" cookie_name ='name'></h1>
    <h1 id ="welcome" cookie_name='visited'></h1>

<script
  src="http://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>
<script type="text/javascript" src="script/js.cookie.js"></script>
<script type="text/javascript" src="script/script.js"></script>
</body>

</html>
--------------------------------------------------------------------------
<script>
    $(document).ready(function(){
        if(Cookies.get('name')===undefined){
            $('form').submit(function(){
         var name = $('input').val()
         Cookies.set('name', name)
         Cookies.set('visited', 1)
        })

        }else{
            $('form').css('display', 'none')
            $('#greeting').append('Welcome ' + Cookies.get('name') + '!')
        }

    })


    if(Cookies.get('visited')===undefined){
            $('#greeting').text('Welcome again!')
        }else{
            $('#greeting').text('Welcome back ' + Cookies.get('name') + '!')
        }

<script>

1 个答案:

答案 0 :(得分:0)

我实际上会使用sessionStorage.setItem('name', name);来存储项目并检查项目是否设置如此 if (sessionStorage.getItem("name"))

选中此link

如果必须使用Cookies,这段代码对我来说就可以了:

  $(document).ready(function () {
    if (Cookies.get('name') === undefined) {
        Cookies.set('name', 'alexis')
        Cookies.set('visited', 1)
    } else {
        console.log('Name is already set');
    }

})

if (Cookies.get('visited') === undefined) {
    console.log('welcome for the first time')
} else {
    console.log('welcome ' + Cookies.get('name'))
}