猿问

请问前端从后台获得的数据处理方式

现在我从后台获取到的数据处理方式都是先创建一个空的字符串。

var result = "";

然后开始构建,例如

result = '<div>' + data.name + '</div>'

最后就放到某个位置。

$("#div").append(result)

最终也会给那些数据加些样式什么的,请教各位大神,我这样处理的方法和流程有问题吗?还有其它的方法吗?谢谢。


DIEA
浏览 617回答 1
1回答

慕哥6287543

建议你可以学习一下前端模板引擎,比如handlebar,比如loadsh像你这样用字符串拼接,要是代码量多了起来,维护起来就很困难了给你贴一段loadsh的demo<ul class="coin_list"></ul>列表<script id="coin-list-template" type="text/template"">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <@ if (packages && packages.length > 0) { @>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <@ _.each(packages, function(data) { @>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p class="coin_num"><@= data.pcs @>币</p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p class="coin_price">售价:<@= data.price @>元</p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <@ }); @>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <@ } @>&nbsp; &nbsp;&nbsp;</script>模板片段代码combinedData = JSON.parse(combinedData);//json对象var compiled = _.template($('#coin-list-template').html());var result = compiled(combinedData)$('.coin_list').html(result);js渲染部分
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答