首先需要说明一下我的需求,后端伙伴给我传过来的数据格式是data.data{arr1[],arr2[],arr3[]}形式,我需要遍历arr1、arr2、arr3数组中的内容,并将它们渲染到html页面中,话不多说,来看看如何实现吧
首先在html模板中,我是根据原型页面用正常的html元素堆积实现,如下所示:
html部分如下所示:
<dt>
<dd>
<span class="hotFunction0">xxx</span>
<span class="hotFunction-value0">xxx</span>
</dd>
<dd>
<span class="hotFunction1">xxx</span>
<span class="hotFunction-value1">xxx</span>
</dd>
<dd>
<span class="hotFunction2">xxx</span>
<span class="hotFunction-value2">xxx</span>
</dd>
</dt>
js部分如下所示:
initHttpServiceUtil.queryAjax({
type: 'get', //请求方式post get 或者delete
url: '接口地址',
data: {},
queryParams: {},
successCallback: function (data) {
if (data.code == 200) {
data.data.arr1.forEach((el,index)=>{
$('.hotFunction'+index).html(el.dataName)
$('.hotFunction-value'+index).html(el.dataValue +"<em>%</em>")
})
data.data.arr2.forEach((item, index) => {
$('.xxx' + index).html(item.dataName)
$('.xxx-value' + index).html(item.dataValue)
})
data.data.arr3.forEach((share, index) => {
$('.xxx' + index).html(share.dataName)
$('.xxx-value' + index).html(share.dataValue)
})
} else {
console.log('接口调用失败')
}
},
async: false
})
这样就能将拿到的数据渲染到html模板里了,可能这样的实现方式存在很多弊端,后续如果学到更好的方法我会继续优化的。大家如果有的方法,多多赐教,感谢!
知识回顾:
1.forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。
注意: forEach() 对于空数组是不会执行回调函数的。
2.ES6标准新增了一种新的函数:Arrow Function(箭头函数)。=>具体用法参照廖雪峰的官方网站上面有详细的说明。我们不但要知其然还要知其所以然。