擴展JS格式化(Format)功能及評論樹

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章