0

嘿,我有一个 json_encode,我试图循环并显示输出,但它不工作,我没有输出 =/

这是我的 js 小提琴:http: //jsfiddle.net/Z4jTc/1/

有人可以解释为什么它不会循环吗?

代码:

var messages = {"1":["2","1","0000-00-00 00:00:00","testing once"],"2":["2","1","0000-00-00 00:00:00","testing twice :)"]};

    for(var id in messages){

            var read = messages[id][0];
            var from = messages[id][1];
            var sent_on = messages[id][2];
            var content = messages[id][3];

            document.write = 'test';
            document.write = '<div class="message_info">';
            document.write =  '<b>From:</b> '+from+'<br/><br/>';
            document.write = '<b>Sent On:</b> '+sent_on;
            document.write = '</div><div class="message_content">';
            document.write = content;
            document.write = '</div> <br/><br/>';

    }​
4

3 回答 3

3

你不断地覆盖这个document.write函数,你从来没有真正调用它。

document.write("test");

是应该如何使用的。

于 2012-05-22T18:38:47.020 回答
1

So many document.write's is pretty slow. You could do it in one call after you parse the object:

var messages = {"1":["2","1","0000-00-00 00:00:00","testing once"],"2":["2","1","0000-00-00 00:00:00","testing twice :)"]};
var output = [];
for(var id in messages){

    var read = messages[id][0];
    var from = messages[id][1];
    var sent_on = messages[id][2];
    var content = messages[id][3];

    output.push('test');
    output.push('<div class="message_info">');
    output.push( '<b>From:</b> '+from+'<br/><br/>');
    output.push('<b>Sent On:</b> '+sent_on);
    output.push('</div><div class="message_content">');
    output.push(content);
    output.push('</div> <br/><br/>');
}​

document.write(output.join(''));

...or place the output in a container on the page...

document.getElementById('destinationContainer').innerHTML(ouput.join(''));
于 2012-05-22T18:53:59.647 回答
0

document.write 是一个函数

利用

document.write('test');

代替

 document.write = 'test';

http://jsfiddle.net/Z4jTc/2/

于 2012-05-22T18:42:29.470 回答