我正在尝试使用 Javascript 读取示例 json 动态插入一大块 html 代码,但无法这样做

I am trying to insert a chunk of html code dynamically with Javascript reading smaple json, but unable to do so

在Whosebug上翻了几个问题,还是没能解决错误。 目的是修改并添加 html 到阅读 JSON 结构的主文档中。

Uncaught TypeError: Cannot read property 'appendChild' of undefined

更新 1:-

  1. 错字已更正,已在代码中标出。
  2. 延迟是在 head 部分的脚本加载时引入的,这可确保在脚本开始执行之前加载整个文档。

我在这里尝试阅读 JSON,然后遍历其内容以添加到我的主要 html 文档中。

var json={  
        "fruit":[  
      {  
         "fruitname":"Apple",
         "location":"data/png/apple.png",
         "quantity":"25",
         "price":"2"
      },
      {  
         "fruitname":"Mango",
         "location":"data/png/mango.png",
         "quantity":"35",
         "price":"3"
      }
   ]
};

//var cards = document.getElementsByClassName("content"); -- corrected typo
var cards = document.getElementById("content");
var fruits = json.fruit;
//alert(fruits.length);
//alert(fruits[1].fruitname);
for (var i = 0; i < fruits.length; i++) {
    var cardelement=document.createElement('div');
    cardelement.className = 'card';
//    alert(cardelement);
    cards.appendChild(cardelement);
    var object = document.createElement('div');
    object.className = 'object';
//    alert(object);
    cardelement.appendChild(object);
    var image = document.createElement('img');
    image.setAttribute("src", fruits[i].location);
    object.appendChild(image);
    var objectback = document.createElement('div');
    objectback.className = 'object-back';
    cardelement.appendChild(objectback);
    var backfruit = document.createElement('div');
    backfruit.className = 'back-fruit';
    backfruit.innerHTML = fruits[i].fruitname;
    objectback.appendChild(backfruit);
    var backprice = document.createElement('div');
    backprice.className = 'back-price';
    backprice.innerHTML = fruits[i].price + "$ per unit";
    objectback.appendChild(backprice);
    var backquantity = document.createElement('div');
    backquantity.className = 'back-quantity';
    backquantity.innerHTML = "In Stock " + fruits[i].quantity + " units";
    objectback.appendChild(backquantity);
    
}
*
{
    margin: 0 0;
    border: none;
    text-align:center
        
}


#header
{
    background-color: #F44336;
    font-family: 'Bungee Shade', cursive;
    font-size: 30px;
    height: 20%
}

#footer
{
    font-family: 'Roboto', sans-serif;
    position: fixed;
    height: 80%;
    width: 100%
}

#content
{
    width: 75%;
    height: 100%;
    border-right: thick solid #F44336;
    float: left;
    text-align: left;
    overflow: scroll
}

#cart
{
    background-color:#3F51B5;
    width: 25%;
    border-bottom: thick dashed #F44336;
    float: right
}

.card
{
    display:inline-block;
    width: 100px;
    height: 100px;
    margin: 40px;
    padding: 20px;
    box-shadow: -1px 9px 20px 4px  #000000;       
    border: 5px solid #F44336;
    border-radius: 26px 26px 26px 26px;
    transition: all .2s ease-in-out
}

.object .object-back
{
    display:block;
    position:static
}

.object-back
{
    display: none
}

.object img
{
    height: 100px;
    width: 100px
}

.back-fruit
{
    font-size: 20px;
    padding-bottom: 5px;
    margin-bottom: 10px;
    border-bottom: thin solid 
}

.back-price
{
    font-size: 12px;
    padding-bottom: 5px
}

.back-quantity
{
    font-size: 10px;
    padding-bottom: 10px
}

.back-pluscart
{
    font-size: 15px;
    background-color: #F44336;
    width: auto
}

.back-pluscart img
{
    height: 30px;
    width: 30px
}

.card:hover 
{
    box-shadow: -1px 9px 46px 11px #000000
}

.card:hover .object
{
    display: none
}

.card:hover .object-back        
{
    display:inline-block;
    opacity: 1
}
<!DOCTYPE html>
<html>
<head>
    <title> The Shopkeeper </title>
    <link href="https://fonts.googleapis.com/css?family=Bungee+Shade" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
    <link rel = "stylesheet" type = "text/css" href = "style/style.css" />
    <script type="text/javascript" src="logic/core.js" defer></script>
    <meta name="viewport" content="width=device-width">
</head>

<body>
    <div id="base">
        
        <div id="header">
            <h1> Fruitkart </h1>    
        </div>
        
        <div id="footer">       
        
            <div id="content">
                
<!--
                <div class="card">
                    <div class="object">
                        <img src="data/png/apple.png" />
                    </div>
                    <div class="object-back">
                        <div class="back-fruit">Apple</div>
                        <div class="back-price">2$ per unit</div>
                        <div class="back-quantity">In Stock 25 pieces </div>
                        <div class="back-pluscart"> <img src="data/png/cart.png" /> </div>
                    </div>
                </div>
 
-->
            </div>
            
            <div id="cart">
                    django
                is a big boy    
            </div>
            
        </div>
    </div>
</body>
</html>

为什么内容未定义

您尝试通过 ClassName 获取内容

var cards = document.getElementsByClassName("content")[0];

但是在你的 html 中找到 content:

<div id="content">

注意ID是内容。将其更改为 class="content" 或将之前的代码更改为 document.getElementByID("content");

两个问题:

  • 没有包含class内容的元素。另一方面,有一个带有 id 的元素。所以你可能想做:

    document.getElementById("content");
    
  • 脚本运行得太快 -- 运行时元素尚未加载。要么将脚本放在结束 </body> 标记之前,要么将代码放在事件处理程序中,例如

    window.addEventListener('DOMContentLoaded', function() {
        // your code
    });
    

您正在尝试访问名称为 class content

var cards =document.getElementsByClassName("content")[0]; 的元素,并且没有 class 名称 content

您可以这样修改您的代码,

var cards = document.getElementById("content");

var json={  
        "fruit":[  
      {  
         "fruitname":"Apple",
         "location":"data/png/apple.png",
         "quantity":"25",
         "price":"2"
      },
      {  
         "fruitname":"Mango",
         "location":"data/png/mango.png",
         "quantity":"35",
         "price":"3"
      }
   ]
};

var cards = document.getElementById("content");
var fruits = json.fruit;
//alert(fruits.length);
//alert(fruits[1].fruitname);
for (var i = 0; i < fruits.length; i++) {
    var cardelement=document.createElement('div');
    cardelement.className = 'card';
//    alert(cardelement);
    cards.appendChild(cardelement);
    var object = document.createElement('div');
    object.className = 'object';
//    alert(object);
    cardelement.appendChild(object);
    var image = document.createElement('img');
    image.setAttribute("src", fruits[i].location);
    object.appendChild(image);
    var objectback = document.createElement('div');
    objectback.className = 'object-back';
    cardelement.appendChild(objectback);
    var backfruit = document.createElement('div');
    backfruit.className = 'back-fruit';
    backfruit.innerHTML = fruits[i].fruitname;
    objectback.appendChild(backfruit);
    var backprice = document.createElement('div');
    backprice.className = 'back-price';
    backprice.innerHTML = fruits[i].price + "$ per unit";
    objectback.appendChild(backprice);
    var backquantity = document.createElement('div');
    backquantity.className = 'back-quantity';
    backquantity.innerHTML = "In Stock " + fruits[i].quantity + " units";
    objectback.appendChild(backquantity);
    
}
*
{
    margin: 0 0;
    border: none;
    text-align:center
        
}


#header
{
    background-color: #F44336;
    font-family: 'Bungee Shade', cursive;
    font-size: 30px;
    height: 20%
}

#footer
{
    font-family: 'Roboto', sans-serif;
    position: fixed;
    height: 80%;
    width: 100%
}

#content
{
    width: 75%;
    height: 100%;
    border-right: thick solid #F44336;
    float: left;
    text-align: left;
    overflow: scroll
}

#cart
{
    background-color:#3F51B5;
    width: 25%;
    border-bottom: thick dashed #F44336;
    float: right
}

.card
{
    display:inline-block;
    width: 100px;
    height: 100px;
    margin: 40px;
    padding: 20px;
    box-shadow: -1px 9px 20px 4px  #000000;       
    border: 5px solid #F44336;
    border-radius: 26px 26px 26px 26px;
    transition: all .2s ease-in-out
}

.object .object-back
{
    display:block;
    position:static
}

.object-back
{
    display: none
}

.object img
{
    height: 100px;
    width: 100px
}

.back-fruit
{
    font-size: 20px;
    padding-bottom: 5px;
    margin-bottom: 10px;
    border-bottom: thin solid 
}

.back-price
{
    font-size: 12px;
    padding-bottom: 5px
}

.back-quantity
{
    font-size: 10px;
    padding-bottom: 10px
}

.back-pluscart
{
    font-size: 15px;
    background-color: #F44336;
    width: auto
}

.back-pluscart img
{
    height: 30px;
    width: 30px
}

.card:hover 
{
    box-shadow: -1px 9px 46px 11px #000000
}

.card:hover .object
{
    display: none
}

.card:hover .object-back        
{
    display:inline-block;
    opacity: 1
}
<!DOCTYPE html>
<html>
<head>
    <title> The Shopkeeper </title>
    <link href="https://fonts.googleapis.com/css?family=Bungee+Shade" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
    <link rel = "stylesheet" type = "text/css" href = "style/style.css" />
    <script type="text/javascript" src="logic/core.js" ></script>
    <meta name="viewport" content="width=device-width">
</head>

<body>
    <div id="base">
        
        <div id="header">
            <h1> Fruitkart </h1>    
        </div>
        
        <div id="footer">       
        
            <div id="content">
                
<!--
                <div class="card">
                    <div class="object">
                        <img src="data/png/apple.png" />
                    </div>
                    <div class="object-back">
                        <div class="back-fruit">Apple</div>
                        <div class="back-price">2$ per unit</div>
                        <div class="back-quantity">In Stock 25 pieces </div>
                        <div class="back-pluscart"> <img src="data/png/cart.png" /> </div>
                    </div>
                </div>
 
-->
            </div>
            
            <div id="cart">
                    django
                is a big boy    
            </div>
            
        </div>
    </div>
</body>
</html>