Js添加消息提示数量

接到个新需求,类似以下这种需求,得把它封装成一个插件

Js添加消息提示数量

后端给返回一个这种数据

var data = [
{
key:"020506",
num:5
},
{
key:"03",
num:2
}
];
key:

02:表示第一层,0205:表示第二层,020506:第三层

如果第三层有新消息,则它本身和它上面的层级都需要显示提示,并显示数量,另外,后端将需要添加提示的元素,都加上了data-newinfo属性,里面的值是它当前的层级。

num:

消息提示的数量

一些注意点
var newinfo = document.createElement('newinfo');

原本想创建一个span元素,但想想还是不太行,因为对应的那个页面很有可能设置了span的样式,而我们是不希望这样的,因此创建了一个特别的元素。

/*
使用说明: data:数据
setInfo():将消息提示添加到页面中 new NewInfo(data).setInfo();
------------------------------------
<div data-newinfo="020505"></div>
var data = [
{
key:"020506",
num:5
},
{
key:"03",
num:2
}
];
*/
function NewInfo(data){
this.data = data;
// 获取所有需要添加新消息提示的元素
this.newinfoDoms = Array.prototype.slice.call(document.querySelectorAll("[data-newinfo]"));
// 样式
this.sty = "padding: 2px 5px;background-color: red;border-radius: 100%;color: #fff;font-size: 12px;vertical-align: 4px;line-height:1;";
}
NewInfo.prototype = {
// 获取所需的信息
getInfo:function(){
var _this = this;
var arr = [];
this.newinfoDoms.forEach(function(item,index){
var isTrue = true;
_this.data.forEach(function(item2,index){
var isNewInfo = item2.key.substring(0,item.dataset.newinfo.length)===item.dataset.newinfo;
if(isNewInfo&&item.dataset.newinfo){
if(isTrue){
arr.push({
'item':item,
'num':item2.num
});
}else{
arr[arr.length-1].num += item2.num;
}
isTrue = false;
}
});
});
return arr;
},
// 添加到相应的页面中
setInfo:function(){
var _this = this;
var arr = this.getInfo();
arr.forEach(function(current,index){
var newinfo = document.createElement('newinfo');
newinfo.style.cssText = _this.sty;
if(current.num>0){
newinfo.innerHTML = current.num;
}else{
newinfo.style.paddingTop = '0';
newinfo.style.paddingBottom = '0';
}
current.item.appendChild(newinfo);
})
}
};

效果

Js添加消息提示数量

上一篇:基于windows环境的Flask网站搭建(mysql + conda + redis)


下一篇:跟着我一步一步的搭建一个基于springcloud的微服务实例