我想这样做:
for (var i = 0; i < massages.length; i++)
{
commentBoxDiv.appendChild(createCommentBox("<?php echo $massages[i]['likes']; ?> people like this.", i));
}
但是我不知道如何打破语法以便访问i
变量
使用一点json_encode和一些创造力,您可以得出如下解决方案:
<script>
var messages = <?php echo json_encode($messages); ?>;
for(var i = 0; i < messages.length; i++) {
commentBoxDiv.appendChild(createCommentBox(messages[i].likes + " %d people like this.", i));
}
</script>
你不能在php代码块中使用JS变量。你必须迭代$massages
数组并从中生成JS对象。