我通过ajax调用得到一个json值,我正在迭代它以使用两个单独的方法设置表的内容和div,如何将这两个函数组合成一个函数,因为我正在迭代数据
function render_table(json_value){
$("tbody").append(
$.map(json_value['comments'], function(event, idx) {
return (
`<tr ">
<td></td>
</tr>`
);
}).join());
}
function render_list(json_value){
$(".history ul").append(
$.map(json_value['comments'], function(event, idx){
return (`
<li>
<div >
</div>
</li>`
);
}).join(' '));
}
答案 0 :(得分:0)
您可以这样做:
function render(json_value) {
$.each(json_value['comments'], function(index, value) {
$("tbody").append(`<tr><td></td></tr>`);
$(".history ul").append(`<li><div></div></li>`);
});
}
答案 1 :(得分:0)
更好:
function render(json_value){
// cache jQuery DOM elements for better performance
var $tbody = $("tbody"),
$historyList = $(".history ul");
// split code functionality into stand-alone pieces which eahc do its own thing
json_value['comments'].forEach(function(index, value){
addTableRow(value);
addListItem(value);
});
function addTableRow( data ){
var template = `<tr>
<td>
<p>${data}</p>
</td>
</tr>`;
$tbody.append(template);
}
function addListItem( data ){
var template = `<li>
<div>${data}</div>
</li>`;
$historyList.append(template);
}
}
这只是订购代码的一种可能方式,因此它更易于管理。有许多设计模式,你应该选择最适合你特定需求的那个。