2017-04-11 38 views
0

我在我的網站上有頁面。比方說,它是:拆分鏈接,保存到cookies並插入到輸入字段

https://example.com/consulting/#ref/testing

和鏈路上有輸入字段:

<input type="text" value="" id="input19" /> 

所以我想要做以下動作:

斯普利特在瀏覽器的URL ,所以我從鏈接中得到了最後一句話(在這種情況下,它是「測試」)。我使用下面的腳本此:

var url = document.URL; 
var match = url.match(/([^/]*)$/); 
console.log(url); 
console.log(match); 

該腳本都會給我在這個例子中的「測試」的鏈接硬道理,我需要這個詞(「測試」)要寫入的cookies瀏覽器之前,被關閉,並從cookie中插入上面提到的ID爲「input19」的輸入字段。

此cookie在刪除前不應更改。當用戶瀏覽網站時,以及在返回上面提到的來自cookie的頁面值之後,也應該在輸入字段中插入。

你可以給我一個解決方案,我怎麼能做到這一點?

回答

0

我會推薦這樣的事情來實現你將要做的事情。

參見:set and get cookies with javascript - stackoverflow

window.onbeforeunload = function(){ 
    var input19 = $('#input19').val(); 
    createCookie(input19,'your-site-cookie',7); 
}; 

window.onload = function(){ 
    var inputx = readCookie('your-site-cookie'); 
    if (inputx) { 
    $('#input19').attr("value", inputx); 
    } 
}; 

function createCookie(name,value,days) { 
    var expires = ""; 
    if (days) { 
     var date = new Date(); 
     date.setTime(date.getTime() + (days*24*60*60*1000)); 
     expires = "; expires=" + date.toUTCString(); 
    } 
    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; 
}