工作中遇到的,记录下来方便日后查看!
这块需要考虑的还是很多的,需要考虑数据去重,数据排序,存储到本地不能超过多少条,超过多少条需要删除等。
Style
<style>
.div{position:relative;}
#note {width: 50%;overflow: hidden;text-align: left;height: 38px;border: 1px solid #ccc;border-radius: 10px;}
#search {width: 141px;height: 37px;font-size: 14px;line-height: 14px;color: #959595;padding-bottom: 2px;}
.hot-list {padding: 10px 0;width: 50%;position: absolute;left: 0px;top: 42px;margin: 0;line-height: 32px;font-size: 14px;background-color: #fff;display:one;border-radius: 4px;border: 1px solid #ccc;}
.hot-list .itemList {text-indent: 15px;}
.hot-list .itemList:hover {background: #e8eaed;}
</style>
HTML
<div class="div">
<input name="note" id="note">
<!--搜索框-->
<button id="search">搜索</button>
<!--历史记录-->
<div class="hot-list"></div>
</div>
JS
<script>
// 备注搜索框方法
function noteMethod() {
var hotList = $(".hot-list");
var input = $("#note");
$(".hot-list").on('mouseover', '.itemList', function () {
$("#note").val($(this).html())
});
// 备注输入框点击
input.click(function () {
if (hisItem.length <= 0) {
return
}
if (!$(this).val()) {
setTimeout(function () {
hotList.show();
}, 100);
}
});
// 备注输入框输入
input.on("input", function () {
if ($(this).val()) {
hotList.hide();
}
});
// 点击隐藏
$(document).click(function () {
hotList.hide();
});
}
noteMethod()
/*
* 备注存储数据处理
*/
var hisTime; //获取时间数组
var hisItem; //获取内容数组
function noteValueInit() {
hisTime = [];
hisItem = [];
// 数据去重
for (var i = 0; i < localStorage.length; i++) {
if (!isNaN(localStorage.key(i))) {
hisTime.push(localStorage.key(i))
}
}
if (hisTime.length > 0) {
hisTime.sort() // 排序
for (var x = 0; x < hisTime.length; x++) {
localStorage.getItem(hisTime[x]).trim() && hisItem.push(localStorage.getItem(hisTime[x]));
}
}
//十条数据,多余删除,同时删除localStorage 数据
if (hisTime.length > 10) {
let len_ = hisTime.length - 10
for (let i = 0; i < len_; i++) {
localStorage.removeItem(hisTime[i]);
}
hisTime.splice(0, len_)
hisItem.splice(0, len_)
}
// 执行noteValueInit(),每次清空之前添加的节点
$(".hot-list").html('');
// 将数据追加itemlist
for (var i = 0; i < hisItem.length; i++) {
$(".hot-list").prepend('<div class="itemList">' + hisItem[i] + '</div>');
}
}
noteValueInit()
// 点击搜索存储数据到localstroge
$("#search").on('click', function () {
var noteValue = $('#note').val();
var time = (new Date()).getTime();
// 将备注的信息放入localStorage做记录
if ($.inArray(noteValue, hisItem) >= 0) {
for (var j = 0; j < localStorage.length; j++) {
if (noteValue == localStorage.getItem(localStorage.key(j))) {
localStorage.removeItem(localStorage.key(j))
}
}
localStorage.setItem(time, noteValue)
} else {
localStorage.setItem(time, noteValue)
}
noteValueInit()
})
//苹果手机不兼容出现input无法取值以下是解决方法
$(".delete").on("click", ".word-break", function () {
var div = $(this).text();
$('#sec').val(div);
});
</script>