2011-10-09 236 views
1

I want to save the content of the <a href> In the localstorage and reuse it. How can i do that? I want to keep the link working. I want to use it to link to webapps (user provided) and i want to achieve that with the localstorage (i am building an online os For personal(and maybe) public use it won't be as big like eyeos or jolicloud).保存的<a href> in the localstorage

+0

簽名/「Thank you,..」不應該添加到問題/回覆中(請參閱http://stackoverflow.com/faq#signatures)。 –

回答

1

If you want to save the whole link (including attributes):

<script> 
function setLinks(){ 
    var all_links = document.getElementById("container").innerHTML; 
    localStorage.setItem("savedLinkHTML", all_links); 
} 
function getLinks(){ 
    var all_links = localStorage.getItem("savedLinkHTML"); 
    if(all_links) document.getElementById("container").innerHTML = all_links; 
} 
window.onload = function(){ 
    getLinks(); 
} 
window.onunload = function(){ 
    setLinks(); 
} 
</script> 
... 
<div id="savedLinks"></div> 

You can create your own functions to dynamically add more links (even images) to the container, which are automatically saved when leaving the page, and shown again when visiting the page.

See also: https://developer.mozilla.org/en/DOM/Storage

+0

在我看來,OP想要保存* href *屬性的值,而不是一大堆HTML。有一個[document.links](http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-7068919)集合可以幫助解決這個問題。 – RobG

+0

'document.links'是指文檔中的所有鏈接。 'document.getElementById(「savedLinks」)。getElementsByTagName(「a」)'只引用容器內的鏈接。調整代碼並不難,只存儲標籤和鏈接。我相信OP在保存數據方面存在問題。 –

+0

使用'getElementsByTagName('a')'將返回所有A元素,這可能是錨點或鏈接(或兩者)。它也是一個函數調用,而不是直接的屬性訪問,所以速度較慢(這可能是不相關的,因爲用戶不會注意到它們之間的差異,除非有非常多的這些差異)。我的問題是存儲* herf *值,你的情況不同。似乎OP還沒有回來,所以在這一點上無所作爲。 :-) – RobG

0

內容爲什麼不搶URL

var url = window.location.href; 

然後將其存儲在鑰匙(i)的值?我知道這聽起來很簡單,但這就是你問的問題......不是嗎?你只需要一個命名系統來檢索。

相關問題