开发者

jQuery templates - Rendering out generic json object

I'm trying to create a 开发者_JAVA百科generic template which will render out JSON objects. The problem is, with all the samples I have seen, they are based on knowing the names of the key...

I started off trying something like this:

<table>
    {{each}}
    <tr>
        <td>$($value[0]}</td><td>$($value[1]}</td>
    </tr>
    {{/each}}
</table>

Now I this isn't generic yet but I was trying this as a start, but it doesn't work...


This was not apparent to me either.

<table>
     <tr>
        {{each $data}}
        <td>${ $index }</td><td>${ $value }</td>
        {{/each}}
     </tr>
</table>

But when you see it you have a D'OH moment.


Here's some code that will get you the keys and values of your JSON object. I'm basing this off of jQuery JSON Associative Array.

for(var key in obj) {
  if (obj.hasOwnProperty(key)){
    document.write("<tr><td>" + key + "</td><td>" + obj[key] + "</td></tr>");
  }
}

It's standard javascript. There's an shorter way to do this in jQuery (mentioned in the previous link).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜