码迷,mamicode.com
首页 > Web开发 > 详细

扩展JS格式化(Format)功能及评论树

时间:2017-07-20 22:28:53      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:js python 格式化 递归

1、JS格式化功能
<script>
        /*
        1. 调用对象方法时,通过调用类的prototype中的方法,可以扩展
        2. 正则表达式 /\w+/g
        3. 字符串replace
                ‘‘.replace(‘alex‘,‘sb‘);
                ‘‘.replace(/\w+/,‘sb‘);
                ‘‘.replace(/\w+/g,‘sb‘);
                ‘‘.replace(/(\w+)/g,function(k,kk){return 11;});
        */
        String.prototype.Format = function(arg){
            /*
            this,当前字符串  "i am {name1}, age is {age9}"
             arg,Format方法传入的参数 {name:‘alex‘,age:18}
             return,格式化之后获取的新内容 i am alex, age is 18
            */
            var temp = this.replace(/\{(\w+)\}/g,function(k,kk){
                return arg[kk];
            });
            return temp;
        };

2、利用以上格式化功能和递归实现评论树

function commentTree(commentList){
            var comment_str = "<div class=‘comment‘>";
            $.each(commentList,function(k,row){
                // var temp = "<div class=‘content‘>"+ row.content +"</div>";
                var temp = "<div class=‘content‘>{content}</div>".Format({content:row.content});
                comment_str += temp;
                if(row.child.length>0){
                    comment_str += commentTree(row.child);
                }

            });
            comment_str += ‘</div>‘;

            return comment_str;
        }


扩展JS格式化(Format)功能及评论树

标签:js python 格式化 递归

原文地址:http://altboy.blog.51cto.com/5440160/1949498

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!