使用localStorage保存数据<li> include <div>

时间:2017-12-01 10:43:17

标签: javascript jquery html html5

我尝试为我的文件夹创建创建LocalStorage数据,我正处于学习阶段。

我的文件夹创建的图片

enter image description here

在JSFiddle中,我只能保存2个元素中的1个,<li><div>,并且在第一个提交中,输入值不会出现在div中。

var count = 1;
// make a function that returns the DOM with updated count
function getNewList() {
  let label = count++;
  var addFolder = '<li>' +
    '<div class="zf-folder" style="width: 232px;">' +
    '<div class="_tabFolder _itemPosition" style="height: 50px;border-bottom:1px groove; user-select: none;">' +
    '<div class="_sideFolder"></div>' +
    '<div class="_iconText" style="width: 215px">' +
    '<div class="ellipsis">' +
    '<div class="_iconFolder">' +
    '<div class="_icon-col">' +
    '</div>' +
    '</div>' +
    '<a href="#folder' + label + '" data-toggle="tab" style="text-decoration: none;"></a>' +
    '</div>' +
    '</div>' +
    '</div>' +
    '</div>' +
    '</li>';
  return addFolder;
}

// Lets save them using submit.
$(".submitButton").click(function() {
  var inputan = $("#input_nameFolder").val();
  $('.nav li:last').find('a').html(inputan).focus();
  document.getElementById("input_nameFolder").value = "";

  // update the result array
  var result = JSON.parse(localStorage.getItem("folderList"));
  if (result == null)
    result = [];

  result.push({
    folder: getNewList(),
    nameFolder: inputan
  });
  // save the new result array
  localStorage.setItem("folderList", JSON.stringify(result));

  // append the new li
  $(".nav").append($(getNewList())); // here i want display div include input value

});

// on init fill the ul
var result = JSON.parse(localStorage.getItem("folderList"));
if (result != null) {
  for (var i = 0; i < result.length; i++) {
    var item = result[i];
    debugger
    $(".nav").append($(getNewList()).html(item.folder)); // and i want display div include input value.
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input_nameFolder" name="nameFolder">
<input type="button" class="submitButton" id="submitButton" value="ADD">

<!-- Result goes here -->
<ul class="nav">
</ul>

MY JSFiddle

2 个答案:

答案 0 :(得分:1)

修改

重新加载页面两次,以防你将之前的HTML存储在localstorage中,因为它的HTML结构错误,我在小提琴脚本的末尾添加了localStorage.removeItem('folderList');来清除以前保存的HTML 您应该在脚本中使用时将其删除,或者您可以使用下面提供的代码块,而不是从小提琴中复制。

首先,你的小提琴有错误的脚本加载顺序。

出现问题时,每次从HTML加载时,您都会附加localStorage,并且会在您重新加载页面时不断添加菜单,就像您说您正在学习所以我会继续使用代码来比较你的脚本的变化。

而不是让事情变得复杂,你应该保持简单,特别是在你开始学习的时候。

您在获取HTML后单独添加文件夹名称,而您可以在函数getNewList中传递名称以生成html以及文件夹名称,并在循环中可以附加它们,请参阅fiddle和对下面代码的引用

var count = 1;

    // make a function that returns the DOM with updated count
    function getNewList(foldername) {
        let label = count++;
        var addFolder = '<li>' +
            '<div class="zf-folder" style="width: 232px;">' +
            '<div class="_tabFolder _itemPosition" style="height: 50px;border-bottom:1px groove; user-select: none;">' +
            '<div class="_sideFolder"></div>' +
            '<div class="_iconText" style="width: 215px">' +
            '<div class="ellipsis">' +
            '<div class="_iconFolder">' +
            '<div class="_icon-col">' +
            '</div>' +
            '</div>' +
            '<a href="#folder' + label +
            '" data-toggle="tab" style="text-decoration: none;"><span class="hyperspan" style="width:100%; height:100%; left:0; top:0;">' +
            foldername + '</span></a>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</li>';
        return addFolder;
    }


    $(".submitButton").click(function () {
        var inputan = $("#input_nameFolder").val();

        // update the result array
        var result = JSON.parse(localStorage.getItem("folderList"));

        if (result == null) {
            result = [];
        }

        let newfolderHTML = getNewList(inputan);

        result.push({
            folder: newfolderHTML
        });

        // save the new result array
        localStorage.setItem("folderList", JSON.stringify(result));

        // append the new li
        $(".nav").append(newfolderHTML); // i want include myDiv

        //clear input 
        $("#input_nameFolder").val('');
    });

    // on init fill the ul
    var result = JSON.parse(localStorage.getItem("folderList"));
    if (result != null) {
        //get the nav reference in DOM
        let nav = $(".nav");

        //clear the html contents
        nav.html('');

        for (var i = 0; i < result.length; i++) {
            var item = result[i];
            nav.append(item.folder);
        }
    }

答案 1 :(得分:0)

如果我真的了解你。我想,你的问题已经完成。我在我的所有项目中都使用了OOP。请试试这个。

/*
 * @params data 'object'
 * @date 01.12.2017
 * Create Template
 *
 */
 function getNewList(data) {
     var addFolder = '<li>' +
            '<div class="zf-folder" style="width: 232px;">' +
                '<div class="_tabFolder _itemPosition" style="height: 50px;border-bottom:1px groove; user-select: none;">' +
                    '<div class="_sideFolder"></div>' +
                    '<div class="_iconText" style="width: 215px">' +
                        '<div class="ellipsis">' +
                            '<div class="_iconFolder">' +
                                '<div class="_icon-col">' +
                                '</div>' +
                            '</div>' +
                            '<a href="#folder' + data.id + '" data-toggle="tab" style="text- decoration: none;">' +
                                '<span class="hyperspan" style="position:absolute; width:100%; height:100%; left:0; top:0;">'+ 
                                    data.value +
                                '</span>'
                            '</a>' +
                        '</div>' +
                    '</div>' +
                '</div>' +
            '</div>' +
        '</li>';
  return addFolder;
 }

/*
* @params storageName 'string'
* @date 01.12.2017
* Get Storage
* It get storage according to parameter.
*
*/
function getStorage(storageName) {
    if(typeof storageName === 'string') {
        var result = JSON.parse(localStorage.getItem(storageName));
            if (result == null)
                return result = [];
            else
                return result;
    }
}

/*
* @params storageName 'string', data 'object'
* @date 01.12.2017
* Get Storage
*
*/
function setStorage(storageName, data) {
    if(typeof storageName === 'string', Array.isArray(data)) {
        localStorage.setItem(storageName, JSON.stringify(data));
        return true;
    }
}

/*
* @params storage 'array', value 'any'
* @date 01.12.2017
* Create Data
*
*/
function createObject(storage, value) {
    if(Array.isArray(storage) && (value !== '' || value !== 'undefined' )) {
        var data = {
            id: storage.length,
            value: value
        }
        storage.push(data);
        return storage;
    }
}  

/*
* 
* @date 01.12.2017
* Clic Action
*
*/
$(".submitButton").click(function() {
    var elm = $("#input_nameFolder"),
        inputan = elm.val(),
        storageName = 'folderList',
        storage = getStorage(storageName),
        data = createObject(storage, inputan);

    var response = setStorage(storageName, data);

    if(response) {
        elm.val('');
        resultBind(storageName);
    }
});

/*
* @params storageName 'string'
* @date 01.12.2017
* Html Bind at Data
*/
function resultBind (storageName) {
    var result = getStorage(storageName);
    if (result != null) {
        for (var i in result) {
            var item = result[i];
            $(".nav").append(getNewList(item)); // i want include input result, 
        }
    }
}

JSFiddle Code