2011-10-09 76 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)的值?我知道这听起来很简单,但这就是你问的问题......不是吗?你只需要一个命名系统来检索。

相关问题