jsRender,json列名与空格

时间:2012-08-28 01:27:26

标签: javascript json jsrender

如何使用包含空格字符的键名“字段ID”引用列/字段名称? “dtTime”也显示为NaN。

<script id="jsRendTmp" type="text/x-jquery-tmpl">
    <li>{{:#Field ID}}</li>
    <li>{{:#dtTime}}</li>

//这是正确的做法(对鲍里斯而言)

<li>{{:#data['Field ID']}}</li>
<li>{{:#data['dtTime']}}</li>

</script>

以下是数据:

  

testData:[           {               “字段ID”:“22”,               dtTime:“8/1/2021”           },           {               “字段ID”:“33”,               dtTime:“8/2/2021”           }       ]

2 个答案:

答案 0 :(得分:3)

你可以得到这样的价值:

{{:#data['Field ID']}}

如果您还想检测密钥名称并进行渲染,请查看以下示例: 03_iterating-through-fields-scenario - 代码here

答案 1 :(得分:0)

您可以使用帮助程序执行此操作:http://jsfiddle.net/imsky/B8ks2/

<script id="jsRendTmp" type="text/x-jquery-tmpl">
    <div style="margin:10px 0">Title</div>
    {{for ~getFields()}}
    <li>{{>key}}: {{>value}}</li>
    {{/for}}
</script>

var data = [ { "Field ID": "22", dtTime: "8/1/2021" }, { "Field ID": "33", dtTime: "8/2/2021" } ];

    $.views.helpers({
        getFields: function( object) {
            var object = this.data;
            var key, value,
                fieldsArray = [];
            for ( key in object ) {
                if ( object.hasOwnProperty( key )) {
                    value = object[ key ];
                    // For each property/field add an object to the array, with key and value
                    fieldsArray.push({
                        key: key,
                        value: value
                    });
                }
            }
            // Return the array, to be rendered using {{for ~fields(object)}}
            return fieldsArray;
        }
    });

$("#content").html($("#jsRendTmp").render(data));