(五)实践JavaScript之加载评论

2017-12-09  本文已影响0人  马梦里

逻辑:
1.获取所有评论,并循环插入评论;
2.插入评论函数里面有个查找,定位到目标weibo下,然后将weibo所属评论插进去;
这就需要在weibo上进行唯一性标识:weibo${weibo.id},因为id不能为纯数字;
一、主函数

var loadsComments = function(){
    log('执行函数')
    apiloadsComments(function(r){
        var comments = JSON.parse(r)
        log('comments', comments)
        for (var i=0; i < comments.length; i++){
            var comment = comments[i]
            insertComment(comment)
        }
    })
}
辅助函数
// 这个逻辑很重要,这个定位目标元素同样重要
var insertComment = function(comment){
    var commenttemplate = commentTemplate(comment)
    log('commenttemplate', commenttemplate)
    var id = comment.weibo_id
    var weiboList = e('#id-weibo-list')
    var weibo_id = comment.weibo_id
    var targetWeibo = weiboList.querySelector(`#weibo${weibo_id}`)
    var weiboCell = targetWeibo.closest('.weiboCell')
    weiboCell.insertAdjacentHTML('beforeEnd', commenttemplate)
}

var apiloadsComments = function(callback){
    path = '/api/weibo/comment/all'
    ajax('GET', path, '', callback)
}

var commentTemplate = function(comment){
    var c = `
        <div class='class-comment-cell'>
            <span class='class-comment-content'>${comment.content}</span>
            <button class='class-comment-delete' data-id=${comment.id}>删除</button>
            <button class='class-comment-edit' data-id=${comment.id}>编辑</button>
        </div>
        <br>
    `
    return c
}
上一篇 下一篇

猜你喜欢

热点阅读