json2html -为包含多个元素的数组中的JSON数据创建内联函数

json2html - Create inline function for JSON data in array w/ multiple elements

本文关键字:数据 JSON 创建 函数 数组 包含多 元素 json2html      更新时间:2023-09-26

我有以下JSON数据:

{"orders":[
{"id":16,"status":"completed","total":"45.00"},
{"id":17,"status":"completed","total":"55.00"}
]}

如何使用json2html将此数据转换为html?${orders.0.total}工作,但我希望它转换所有的顺序,而不仅仅是数组0。

我试过这个答案的解决方法,但是行不通。

这是我的:

<body>
    <ul id="list"></ul>
</body>
<script type="text/javascript">
    //List items
    var myjson = [{"orders":[
                 {"id":16,"status":"completed","total":"45.00"},
                 {"id":17,"status":"completed","total":"55.00"}
                 ]}];
    //List item transform
    var orderTransform = {"tag":"div","html":"${total}"}
    var transform = {"tag":"div","children":function(){
        return( json2html.transform(this,orderTransform) );
    }};
    $(function(){
        //Create the list
        $('#list').json2html(myjson,transform);
    });
</script>

thx

您的转换应该修改为:

var transform = {"tag":"div","children":function(){
        return( json2html.transform(this.orders,orderTransform) );
}};

注意thisthis.orders的变化,因为根变换引用了{orders: [...]}对象,所以在子函数中有必要指定用作数据的新数组。

原始代码将this作为子对象的数据传递,这会使json2html尝试使用orderTransform来呈现{orders: [...]}对象,这是不正确的,因此显式指定该转换的数据在orders字段中是很重要的。