<script>
var quill = new Quill('#editor-container', {
modules: {
formula: true,
syntax: true,
toolbar: '#toolbar-container'
},
placeholder: 'Compose an epic...',
theme: 'snow'
});
$(function () {
var timer = null;
// 简单节流器 每隔三秒储存数据
function throttle() {
if (timer == null) {
timer = setTimeout(saveLocal, 3000);
} else {
return;
}
}
$(".ql-editor").on("keydown", function () {
if ($('.title input').val() != '') {
throttle();
} else {
alert("请先输入标题");
}
});
var title = null;
$('.title input').on({
'focus': function () {
title = $(this).val();
}, 'blur': function () {
var new_title = $(this).val();
if ($.trim(new_title) != $.trim(title) && $.trim(title) != '') {
Titlechange(title, new_title);
}
}
});
//获取索引
geturl();
//当标题改变时 本地储存同步改变
function Titlechange(obj1, obj2) {
var data = JSON.parse(window.localStorage.getItem('biji'));
$(data).each(function (i, data) {
if (data[0].title == obj1) {
data[0].title = obj2;
return;
}
})
window.localStorage.setItem("biji", JSON.stringify(data));
}
//实时记录 笔记内容
function saveLocal() {
clearTimeout(timer);
timer = null;
var $title = $('[name="title"]').val();
var $html = $(".ql-editor").html();
var content = [{title: $title}, {text: $html}];
if (window.localStorage.getItem("biji") == null) {
window.localStorage.setItem("biji", JSON.stringify(new Array()));
} else {
var data = JSON.parse(window.localStorage.getItem("biji"));
var flag = false;
if (data.length != 0) {
$(data).each(function (i, data) {
if (data[0].title == $title) {
data[1].text = $html;
flag = true;
return;
}
})
window.localStorage.setItem("biji", JSON.stringify(data));
}
if (!flag) {
data.push(content);
window.localStorage.setItem("biji", JSON.stringify(data));
}
}
}
});
//获取索引
function geturl() {
var index = parseInt(location.href.split("?index=")[1]);
if (index != null) {
var data = JSON.parse(window.localStorage.getItem("biji"));
$('[name="title"]').val(data[index][0].title);
console.log(data[index][1].text);
$(".ql-editor").html(data[index][1].text);
} else {
return;
}
}
</script>
基于localstorage写的小项目