【问题标题】:Display localStorage value in html header在 html 标头中显示 localStorage 值
【发布时间】:2014-09-22 18:13:58
【问题描述】:

我想向用户发送欢迎消息,并使用他填写表单后更新的 localStorage 中的姓名。

例如 =“你好约翰!”里面 对于我想使用的代码 - “你好”+变量名+“!”

我尝试了几种方法,但都没有成功。

这是 HTML:

 <div data-role="header" data-theme="b" id="displayname">
        <h1 >
          <!--Here I Want the Welcome Message-->
        </h1>
        </div>

存储在 localStorage.name 中的名称,我需要显示该值

很高兴听到一些建议,谢谢。

这是本地存储脚本:

function saveSettings() {
localStorage.name = $('#your_name').val();
localStorage.id = $('#id_number').val();
localStorage.email = $('#email_address').val();
localStorage.bdate = $('#birth_date').val();
localStorage.mphone = $('#mobile_phone').val();
localStorage.hphone = $('#home_phone').val();
localStorage.lnumber = $('#license_number').val();
} 

【问题讨论】:

  • 显示 locastorage 项目的事情很简单。您需要的是关于如何存储和检索本地存储项目的全面指南——这是基本指南——w3schools.com/html/html5_webstorage.asp——这里是更全面的指南——htmldog.com/guides/javascript/advanced/localstorage
  • 我试过这种方式也没有成功,你有机会告诉我你将使用的代码吗?
  • 那么当你这样做时 (var name = localStorage.getItem("name");) 什么都没有回来?

标签: jquery variables jquery-mobile append local-storage


【解决方案1】:

正如承诺的那样,我为您准备了一个演示。为了便于理解,我在代码中放了很多 Remarks。它不使用 Json,而是使用异步函数来循环本地存储。它工作得很好。最重要的是它非常可靠,并且永远不会破坏本地存储。

您可以添加和删除用户,但可以接受各种可能性,因为您将从备注中阅读。它可以作为基础数据库在LocalStore中存储数据。

演示

http://jsfiddle.net/3vynv918/

jQuery

    $( document ).ready(function() {

    // an async function to loop around with ease
    var asyncFor = function(params) {

        var defaults = {
          total: 0,
          limit: 1,
          pause: 10,
          context: this
        },
          options = $.extend(defaults, params),
          def = $.Deferred(),
          step = 0,
          done = 0;

        this.loop = function() {
          if (done < options.total) {
            step = 0;
            for (; step < options.limit; step += 1, done += 1) {
              def.notifyWith(options.context, [done]);
            }
            setTimeout.apply(this, [this.loop, options.pause]);
          } else {
            def.resolveWith(options.context);
          }
        };

        setTimeout.apply(this, [this.loop, options.pause]);
        return def;
      };



    $(document).on( "click", "#sub", function() {
    var name = $('#user').val();

     var id ="";

     //create a random id for the user so we can distinguish him in local storage incase of Possible duplicate first names

     var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < 10; i++ )

    id += possible.charAt(Math.floor(Math.random() * possible.length));

    //store the data from the form to localstorage. we use user as the kind of dataset so it will enable to store as many datasets as possible. eg stock, places, locations. So you can group data. In this example we are storing Users

    localStorage.setItem(id, 'user['+name+'#name]' ); // you can add many form items by seperating them by # eg name#surname#address. I put #name as an example, but in this demo we dont read that. So we call that spare data as it does nothing, although it gets stored for each user.

    $('#usersname').html(name);

    show_localstore()

    });

    // get all items from local storage and show them
    function show_localstore() {
    var mylistitems = "";
    $('#storage').empty();

    asyncFor({
      total: localStorage.length,
      context: this
    }).progress(function(step) {

    var propertyName = localStorage.key(step);
    var keyv = propertyName;
    var value = localStorage.getItem(propertyName);

 //check the dataset if its user. If you have other datasets then change user to that dataset  
    if (value.indexOf('user') > -1) {

    var matches = value.match(/\[(.*?)\]/);

    if (matches) {

    var words = matches[1];

    var match = words.split('#');

    var username = match[0];  // matches the first item, if you have many then set up variables and change the match value eg surname = match[1] address = match[2] etc

    $("#storage").append('<p><a>user_id='+keyv+'<a>--username='+username+'</a></p>');   

    }}

    }).done(function() {

    });

    };

    //delete localstore item by selecting the User_id value. 
    $(document).on( "click", "#delsub", function() {  
    var id  = $('#deluser').val();
    localStorage.removeItem(id);
     show_localstore()   
    });

     show_localstore()     
    });

【讨论】:

  • 哇!非常感谢你。但不幸的是你不明白我的问题,我已经在使用 ajax/json 数据库了。我只想将 localstore.name 值写入 dom 内的 div 中。
  • 没关系,不用担心。你真的设置了本地存储吗?如果您可以发布到目前为止的代码并更新我可以提供帮助的问题。如果您使用 chrome,请打开开发人员工具并在控制台中输入。 localstorage --- 你看到任何数据了吗?
  • 是的,我看到了 - bdate:“1994-03-14”email:“ofiro.ohayon@gmail.com”hphone:“089750585”id:​​“312545197”length:7lnumber:“574- 444-333"mphone:"0504229998"名称:"ofiro.ohayon@yahoo.com"
猜你喜欢
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 2020-09-11
  • 1970-01-01
  • 1970-01-01
  • 2021-06-06
  • 1970-01-01
  • 2021-02-24
相关资源
最近更新 更多