Js添加消息提示数量

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

857662-20161129143558537-61302724.png

后端给返回一个这种数据

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);
        })
    }
};

效果

857662-20161129144728740-1344040174.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值