appendChild 不会工作?

appendChild wont work?

我正在尝试制作一个收件箱,当您首次加载页面或单击按钮时会显示消息,但没有任何显示。我做错了什么?

var inbox = document.getElementsByClassName("inbox").item(0);
var inbox_button = document.getElementById("messages");
inbox_button.addEventListener("click", showMessages);
showMessages();

function showMessages() {
  var messages = "<?php echo $inbox ?>";
  var inbox_table = document.createElement("table");
  var inbox_content =
    "<tr>" +
    "<th>From</th>" +
    "<th>Subject</th>" +
    "<th>Date</th>" +
    "</tr>";
  for (i = 0; i < messages.length; i++) {
    inbox_content = inbox_content +
      "<tr>" +
      "<td>" + messages[i][1] + "</td>" +
      "<td>" + messages[i][2] + "</td>" +
      "<td>" + messages[i][5] + "</td>" +
      "</tr>";
  }
  inbox_table.innerHTML = inbox_content;
  inbox.appendChild(inbox_table);
}
<div class="inbox">
  <button id="messages" type="button">Inbox</button>
  <button id="new_message" type="button">New Message</button>
</div>

您将消息填充为引号之间的字符串 var messages = "<?php echo $inbox ?>";,并且您的逻辑需要一个二维数组,因此变量 $inbox 应该 return 文本作为 Javascript的数组数组,例如:

PHP:

$inbox = '[["Text-1-1", "Text-1-2", "Text-1-3"], ["Text-2-1", "Text-2-2", "Text-2-3"]]';

Javascript(直行,无引号):

var messages = <?php echo $inbox ?>;