89%

常用功能总结

相同内容隔行变色

最近做的一个项目,通过接口渲染数据后,使相同内容的表格行为同一种颜色,以下是代码实现。 页面基于jquery,使用artTemplate模板引擎

CSS代码

.color_0 {
    background: #ccc;
}

.color_1 {
    background: #fff;
}

HTML代码

<table class="main-table">
</table>
<script id="insurerTemplate" type="text/html">
    <tr><td class="item">张三</td></tr>
    <tr><td class="item">李四</td></tr>
    <tr><td class="item">张三</td></tr>
    <tr><td class="item">李四</td></tr>
</script>

数据模拟

var dataList = {
    data: [
        {
            id: 1,
            insurerId: 1,
            insurerName: '张三'
        },
        {
            id: 2,
            insurerId: 1,
            insurerName: '张三'
        },
        {
            id: 3,
            insurerId: 2,
            insurerName: '李四'
        },
        {
            id: 4,
            insurerId: 3,
            insurerName: '王五'
        },
        {
            id: 5,
            insurerId: 3,
            insurerName: '王五'
        }
    ]
};

JS代码

$(function() {
    function changeColor(conf, data) {
        this.init.apply(this, arguments);
    }
    changeColor.prototype = {
        check: function() {
            var _self = this;
            $(_self.table).find('.item').each(function(k, v) {
                var html = $(v).text(),
                    flag = false,
                    hasindex = 0,
                    color = 0;
                $.each(_self.temparr, function(index, item) {
                    if (html == item.t) {
                        flag = true;
                        hasindex = index;
                    }
                });
                //如果不存在的话
                if (flag === false) {
                    try {
                        var lastcolor = _self.temparr[_self.temparr.length - 1].color;
                        color = lastColor >= 1 ? 0 : lastColor + 1;
                    } catch (e) {}
                    _self.temparr.push({
                        t: html,
                        color: color
                    });
                } else {
                    //如果已经存在的话
                    color = _self.temparr[hasindex].color;
                }
                $(v).addClass('color_' + color);
            });
        },
        init: function(conf) {
            var _self = this;
            _self.temparr = [];
            _self.table = conf.table || '';
            _self.check();
        }
    };

    var renderHtml = template('insurerTemplate', dataList);
    $('.main-table').html(renderHtml).promise().done(function(){
        new changeColor({
            table: '.main-table'
        });
    });
});

Blog

life

Project