使用json时无法将属性'innerHTML'设置为null

时间:2019-07-22 20:03:27

标签: javascript html

我试图使用此代码生成列,并试图使用json将名称放入框中。但是,当我尝试运行代码时,标题中会出现错误。

这是代码:

<script type="text/javascript">
  $(document).ready(function() {
     console.log("registered stories ready!");

    var i;
    for (i = 0; i < 12; i++) { 
      $("#stories").append(
        "<div class='col-sm-12 col-md-3 col-lg-3'>\
          <a href='C:/Users/Vlad/Desktop/Coursera-Assignments-master/docs/Sample Stream.html'>\
            <img src='img/placeholder.jpg' alt='placeholder' class='images'> <br>\
            <p class='who-is-reading' id='firstname'>Firstname is reading</p>\
            <p class='book-title'>Story Title</p>\
          </a>\
        </div>");
  }
                              });
</script>

<script>
  var myObj, x;
  myObj = {
    "age":30,
    "name":[ "Ford", "BMW", "Fiat" ]
  };
  x = myObj.name[0];
  document.getElementById("firstname").innerHTML = x;
</script>

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

您的问题是您正在将HTML附加到Document.Ready事件上,但是您要在附加HTML之前访问DOM。这是有关如何解决此问题的示例

<script type="text/javascript">
    $(document).ready(function() {
        console.log("registered stories ready!");

        var i;
        for (i = 0; i < 12; i++) { 
            $("#stories").append(
            "<div class='col-sm-12 col-md-3 col-lg-3'>\
                <a href='C:/Users/Vlad/Desktop/Coursera-Assignments-master/docs/Sample Stream.html'>\
                <img src='img/placeholder.jpg' alt='placeholder' class='images'> <br>\
                <p class='who-is-reading' id='firstname-" + i + "'>Firstname is reading</p>\
                <p class='book-title'>Story Title</p>\
                </a>\
            </div>");
        }

        var myObj, x;
        myObj = {
            "age":30,
            "name":[ "Ford", "BMW", "Fiat" ]
        };
        x = myObj.name[0];
        document.getElementById("firstname-1").innerHTML = x;
    });
</script>

请注意document.getElementById("firstname-1").innerHTML也位于Document.Ready块中。此外,请确保您的ID不正确