2017-06-14 86 views
-1

我需要在文本框中保存一个字符串,并使其发生,当“设为默认值”框被选中并且按下按钮时,ID的输入将被保存作为用户的cookie。 IE浏览器。我将输入“TEST”,下次打开应用程序时,它会记住在搜索到的&中输入的输入。通过cookies存储数据

我会提供一个来自用户界面的图像,所以你会基本了解它是怎么样的;

enter image description here

我有双方的项目; (排除CSS)JS和HTML。目前我在cookie.js中的代码看起来如下;

function setCookie(cname, cvalue, exdays) { 
    var d = new Date(); 
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); 
    var expires = "expires=" + d.toGMTString(); 
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; 
} 

function getCookie(cname) { 
} 

function checkCookie() { 
} 

我还没有真正尝试过什么具体的,我已经试过checkCookie和的getCookie函数工作得到这个工作,但至今无果。

在HTML中,我只在体内编码;

<body id="body" style="max-height: 100%;" onload="checkCookie()"> 

<form onsubmit="return false" id="searchform"> 
    <input type="text" id="field" placeholder="Search timetable" 
    maxlength="100" autocomplete="off"> 

    <label for="setDefault" id="mlabel"><input type="checkbox" 
    id="setDefault" data-role="none" />Set as default</label> 
    <input type="button" value="Search" id="search" 
    class="ui-btn ui-input-btn 
    ui-corner-all ui-shadow" onclick="executeSearch()" /> 
</form> 

</body> 

所以我的问题是;如何将我在文本框中键入的字符串存储起来,以及如何在再次打开页面时获取值?

+1

而你的问题是什么?如何从cookie中获取价值? – George

+0

@George将问题编辑给OP。 –

+0

你可以检查[这个答案](https://stackoverflow.com/a/41344722/2534646)它会帮你 – Curiousdev

回答

2

一个函数来设置cookie

function setCookie(cname, cvalue, exdays) { 
    var d = new Date(); 
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); 
    var expires = "expires="+d.toUTCString(); 
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; 
} 

一个函数来获取一个Cookie

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

当你做了搜索,设置搜索关键字来使用网站

function executeSearch(){ 
    var setDefault = document.getElementById('setDefault').checked; 
    if(setDefault){ 
     var keyword = document.getElementById('field').value; 
     setCookie('search-keyword', keyword, 360); 
    } 

    //Do the search 
} 

现在,当加载页面检查cookie的存在,加载以前的搜索关键字

function checkCookie(){ 
    var previousKeyword = getCookie('search-keyword'); 
    document.getElementById('field').value = previousKeyword; 
} 

你可以阅读更多关于cookies的信息here

1

所以,如果你的问题是你如何可以存储与JS浏览器中的Cookie,则这是anwser:

使用JavaScript,cookie可以这样创建:

document.cookie = "username=John Doe"; 

您还可以添加到期日期(UTC时间)。默认情况下,当浏览器关闭时,Cookie将被删除:

document.cookie = "username=John Doe; expires=Thu, 18 Dec 2017 12:00:00 UTC"; 

通过路径参数,您可以告诉浏览器cookie属于哪个路径。默认情况下,Cookie属于当前页面。

document.cookie = "username=John Doe; expires=Thu, 18 Dec 2017 12:00:00 UTC; path=/"; 

使用JavaScript,饼干可以这样写:

var x = document.cookie; 

而要访问您输入的文本框,你必须给函数的参数,当你调用它: myfunction(myinput);

希望这有助于你