开发者

JS output from data structure to table

Data Structure

var X = {
   a: [{name:"john", phone:777},{name:"john", phone:777},{name:"john", phone:777}],
   b: [{name:"john", phone:777},{name:"john", phone:777},{name:"john", phone:777}],
   c: [{name:"john", phone:777},{name:"john", phone:777},{name:"john", phone:777}],
   d: [{name:"john", phone:777},{name:"john", phone:777},{name:"john", phone:777}]
}

Function

function showTable(trnum,X,a) {
    开发者_如何学编程var Tablecode = "<table><tbody>";
    for (var i=0; i< X.a.length;i++) {
        for (var j=0; j< trnum; j++) {
            Tablecode += "<tr><td>"+X.a[i].name+"</td><td>"+X.a[i].phone+"</td></tr>";
        }
    }
    Tablecode += "</tbody></table>";
    $("#elem").append(Tablecode);
}

Markup

<body>
    <button onclick="showTable(4,X,"a");"></button>
    <div id="elem">
    </div>
</body>

I'm trying to output data to table according to letter. one object on one table row.(all objects in table within one letter). this code doesn't work- unexpected token "}". oddly enough, it points to <div id="elem"> line. but there's no such character! How can I fix this?

UPDATE: thanks, error disappeared... but it outputs the whole structure, how do I make it output only 'a' objects?


<button onclick="showTable(4,X,"a");"></button>

should be like that (doublequotes):

<button onclick="showTable(4,X,'a');"></button>

Compare this one to yours (see .a and [a])

for (var i=0; i< X[a].length;i++){
 for (var j=0; j< trnum; j++){
 Tablecode += "<tr><td>"+X[a][i].name+"</td><td>"+X[a][i].phone+"</td></tr>";
 }

}

Feature reading about javascript notations


From tossing your code into a fiddle and getting it to run, I noticed that your button is a failure point. You have to surround the 'a' with SINGLE quotes.

http://jsfiddle.net/YaZp2/1/

EDIT: Also, edited the output code added the ability to actually see if it works.


Double quotes used to delimit the onclick and also the params within.

Try

<button onclick="showTable(4,X,'a');">
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜