选择文本并添加到localstorage

时间:2015-03-30 07:40:59

标签: javascript jquery html5

我一直在使用一个简单的html5笔记应用程序,并希望扩展它。

我希望能够在页面上选择一些文本并将其添加为注释。我不确定是否要创建新功能或修改已存在的功能。

我已将下面的代码添加到了localstorage中。

我还包含了一个指向github页面的链接,其中html代码为:https://github.com/oxhey/Notes-Manager

if(newItem){ // don't push when generating from localStorage
            allTitles.push(listTitle);
            allLists.push({'title': listTitle, 'note': listNote});

            localStorage.setItem('allLists',JSON.stringify(allLists));
            localStorage.setItem('allTitles',allTitles);
        }

        return listContainer;
    };

HTML:

 <form class="form-horizontal" onsubmit="return false;"  role="form" id="newListForm">
                <div class="form-group">
                    <label for="newListInput" class="col-sm-2 control-label">Title<span>*</span></label>
                    <div class="col-sm-5">
                        <input type="text" required="true" class="form-control" name="newListTitle" id="newListInput" placeholder="List Title" onblur=' this.value=this.value.replace(/(^\s*)/g, "") ; '>
                    </div>
                </div>

                <div class="form-group">
                    <label for="newNoteInput" class="col-sm-2 control-label">Note<span>*</span></label>
                    <div class="col-sm-5">
                        <textarea required class="form-control" name="newListNote" id="newListNote" placeholder="Write Note" ></textarea>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-5">
                        <button type="submit" id="submitButton" class="btn btn-primary">Save</button>
                    </div>
                </div>
            </form>

1 个答案:

答案 0 :(得分:0)

你可以在Javascript中做到这一点。使用以下代码:

if(window.getSelection){
    selectedText = window.getSelection();
}else if(document.getSelection){
    selectedText = document.getSelection();
}else if(document.selection){
    selectedText = document.selection.createRange().text;
}

Selection | MDN

修改

尝试使用以下JS代码和HTML:

function submitForm(){
  var listTitle = document.getElementById("newListInput").value;
  var listNote = document.getElementById("newListNote").value;

  console.log(listNote);


  // not sure why you have the following 2 lines
  //if(newItem){ // don't push when generating from localStorage
    //allTitles.push(listTitle);  

  var allLists = [];

    allLists.push({'title': listTitle, 'note': listNote});

    localStorage.setItem('allLists',JSON.stringify(allLists));
    localStorage.setItem('allTitles',allTitles);
//  }
}
//return listContainer;
//};