你如何从localStorage调用url

时间:2012-05-15 21:16:18

标签: javascript local-storage

我想在设置页面上将网址保存到localStorage。然后我需要一个超链接或按钮,当单击时,转到该URL。尽量不要使用jquery。

<!doctype html>
<html>
<head>
<title>Local Storage URL</title>

<script type="text/javascript"> 
function save() {
    var myURL = document.getElementById('url');
    localStorage.setItem('url', myURL.value);
}

function load() {
    var storedValue = localStorage.getItem('url');
    if(storedValue) {
        document.getElementById('url').value = storedValue;
    }
}

</script>

</head>

<body onLoad="load()">
<input type="text" id="url" />
<input type="button" value="save" onclick="save()" />
<p>
<-- Here is where I am stuck below --><br>
<a href="('myUrl')">Link to localStorage Address</a>
</body>
</html>    

1 个答案:

答案 0 :(得分:1)

你应该设置锚标记的href和innerHTML,

<a id="link" href="('myUrl')">Link to localStorage Address</a>

function load() {
    var storedValue = localStorage.getItem('url');
    var linkTag = document.getElementById('link');
    var urlInput = document.getElementById('url');
    if(storedValue) {
        urlInput.value = storedValue;
        linkTag.href = storedValue;
        linkTag.innerHTML = storedValue;
    }
}

DEMO