appendChild不会工作?

时间:2017-05-05 21:31:50

标签: javascript html dom appendchild

我试图创建一个收件箱,当您第一次加载页面或单击按钮时会显示消息,但没有任何内容显示。我做错了什么?



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);
}
&#13;
<div class="inbox">
  <button id="messages" type="button">Inbox</button>
  <button id="new_message" type="button">New Message</button>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

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