如何使用knockout js在按钮点击时在localstorage中存储值?

时间:2013-08-16 07:17:44

标签: html5 knockout.js

这是我的代码,但是当我在输入框中输入文本后,我点击保存按钮,然后文本保存到下拉列表中,但是这个文本没有存储在本地存储中,对于这个我使用knockout.js

 <form style="margin-top: -25px;">
            <button id="buttonSave" type="submit" style="margin-left: 1156px;">Save</button>

         </form>

    <div id="labelList" class="btn-group" style="margin-top: -595px;margin-left: 3px;">
        <input id="editExistannotation" data-bind="value: annotationList" class="editAnnotationList textArea" type="text" placeholder="Edit existing annotation"/>
    <select data-bind="options: area"></select>

    </div>

----------------------------------------------------

  var addHandle = function () {
                this.items = ko.observableArray();
                this.add = function (item) { this.items.push(item); }
                this.remove = function (item) { this.items.remove(item); }
                this.clear = function () { this.items.removeAll(); }
            }
            var addHandler = new addHandle();
            ko.applyBindings(addHandler, document.getElementById("slider"));

            $("#buttonSave").click(function () {
                var label_object;
                var labelText = document.getElementById("textarealabel");
                var labelObject = new Object();
                labelObject.textarealabel = labelText.value;
                localStorage.setItem('label_object', JSON.stringify(labelObject));
                $("#ddlList").prepend("<option value='0'>" + localStorage.getItem(label_object) + "</option>");
                return false;
            })
 var existAnnotationmodel = new function () {

                var labelObject = $('#textarealabel').val();
                this.annotationList = ko.observable();
                this.area = ko.observableArray();
                this.append = ko.computed(function () {
                    this.area.push(this.annotationList());
                    localStorage.setItem('labelObject', JSON.stringify(labelObject));
                }, this);
            }
            ko.applyBindings(existAnnotationmodel);

1 个答案:

答案 0 :(得分:0)

现在,当您在输入类型=“文本”中键入文本并单击按钮时。该文本将添加到选项和本地存储中。

我还删除了不相关的代码。

<form >
    <button id="buttonSave" type="submit" data-bind="click:append" >Save</button>
</form>
<div id="labelList" class="btn-group" >
    <input id="editExistannotation" data-bind="value: annotationList"  type="text" />
    <select data-bind="options: area"></select>
</div>

var VM  = function () {

    this.annotationList = ko.observable();
    this.area = ko.observableArray();
    this.append = function () {
        this.area.push(this.annotationList());
        localStorage.setItem('labelObject',this.annotationList());
        localStorage.setItem('labelObjectList',this.area());
    };
};

var existAnnotationmodel = new VM();

ko.applyBindings(existAnnotationmodel);

See fiddle