2017-06-14 84 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);

希望這有助於你