简体   繁体   English

如何创建本地存储?

[英]How to create local storage?

My website has tabs and within that tab, info cards and a checkbox on the right hand side that highlights the card in a different colour. 我的网站有标签,在该标签内,信息卡和右侧的复选框,以不同的颜色突出显示卡。 How can I makes it so that onclick the highlighting is saved even if the page is refreshed or if the page is sent as a link? 即使刷新页面或将页面作为链接发送,我怎么能这样才能保存突出显示? Full code here: http://codepen.io/johnsonshara/pen/obGjGN (below code not in code pen version) 完整代码在这里: http//codepen.io/johnsonshara/pen/obGjGN (下面的代码不在代码笔版本中)

What I have tried: 我尝试过的:

function save () {
    var fieldValue = document.getElementById('like').value;
    localStorage.setItem('checkbox', 'fieldValue');
}

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

And This: 和这个:

function save() {
if(typeof(Storage) !== "undefined") {
if (localStorage.setItem) {
localStorage.setItem = document.getElementById("like");
} else {
localStorage.getItem = .hasClass.apply;
}
document.getElementById("like").innerHTML = localStorage.toString;
} else {
document.getElementById("like").innerHTML = "Sorry, an error occured.";
}
}

html HTML

<input type="checkbox" class="faChkRnd" onclick="save()" id="like" >    

Check out the following link to see how you can use the local storage: 请查看以下链接,了解如何使用本地存储:

http://www.w3schools.com/html/html5_webstorage.asp http://www.w3schools.com/html/html5_webstorage.asp

Quick example code of how it would work: 它的工作原理的快速示例代码:

// Put the object into storage
localStorage.setItem('testObject', "testing");

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');

Example using your example code above: 使用上面的示例代码的示例:

 alert(load()); $(document).on("click", "#clickME", function(){ save(); }); function save () { var fieldValue = "testString"; localStorage.setItem('checkbox', fieldValue); } function load () { var storedValue = localStorage.getItem('checkbox'); if(storedValue) { console.log("VALUE :" + localStorage.getItem('checkbox')); } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button id="clickME">Click me</button> 

or if the page is sent as a link 或者如果页面作为链接发送

You should store your data as a url parameter not in the local storage. 您应该将数据存储为不在本地存储中的url参数。 So anyone that click on the link will get the data. 所以点击链接的任何人都将获得数据。

See this link to know more about using url parameters with JS: How to get the value from the GET parameters? 请参阅此链接以了解有关在JS中使用url参数的更多信息: 如何从GET参数中获取值?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM