如何让我的新构造函数工作?我在Visual Studio Code中使用Javascript



我的JS代码如下所示。但当我打开页面时,上面写着";Uncaught TypeError:无法设置null的属性"innerHTML";

我试图将NewItem构造函数更改为函数。但是VSC一直说我应该把它声明为一个类。我首先转换了它,因为构造函数也不能作为函数工作。

class NewItem {
constructor(name, date, price) {
this.itemName = name;
this.itemDate = date;
this.itemPrice = price;
}
}

const onListItem = new NewItem("John", "Date", "Price");
document.getElementById("demo").innerHTML = onListItem.itemDate;

HTML看起来像这个

<!DOCTYPE html>
<html lang= "en">
<head>
<link rel="stylesheet" href="ShopListStyle.css">
<meta name="viewport" content="width=device-width" initial-scale=1.0>   
<title>Shopping List</title>   
</head>
<body>
<script src="ShopListScript.js"></script>
<div id="container">

<div id="inputbox" class="section">
<form id="labels-form">
<label><h2>Shopping List</h2></label>
<input id="labels-name" class="labels-input" type="text" value="Item Name"></input>
<input id="labels-date" class="labels-input" type="text" value="Date of Purchase"></input>
<input id="labels-price" class="labels-input" type="text" value="Item Price"></input>
<button id="labels-button">Add to List</button>
<p id="demo"></p>
</form>
</div>
<div id="shopListBox" class="section">

<!--Need to add a delete button/ Maybe a quantity button down the road-->
<table id="shopList">

<caption><h2>Spending List</h2></caption> 
<thead id="table-header">   
<tr>
<th class="table-header" id="table-name">name</th>
<th class="table-header" id="table-date">date</th>
<th class="table-header"id="table-price">price</th>
<th class="table-header" id="table-delete">delete</th>
</tr>
</thead>
<tbody id="table-body">
<tr class="newRow">
<td class="new-item" id="item-name">item</td>
<td class="new-item" id="item-date">item</td>
<td class="new-item" id="item-price">item</td>
<td class="new-item"><button class="item-button">Delete</button></td>
</tr>
</tbody>
<tfoot id="table-footer">
<tr>
<td id="item-price-sum" colspan="4" style="width: 100%" >Sum of Prices</td>
</tr>
</tfoot>
</table>

<!--The sum of all the prices will go somewhere here-->
</div>
</div>
</body>
</html>

您的JavaScript代码正试图使用id demo(<p id="demo"></p>(访问此元素:
document.getElementById("demo").innerHTML = onListItem.itemDate;

您的脚本添加在打开的正文标记处。。。

<body>
<script src="ShopListScript.js"></script>
...

这意味着CCD_ 3元素还不存在。

解决方案:将脚本放在结束正文标记之前:

...
<script src="ShopListScript.js"></script>
</body>
</html>

您也可以尝试设置

<script src="ShopListScript.js" defer="defer"></script>

因为javascript会阻塞DOM的渲染,所以我们应该把放在最后

就像彼得·克雷布斯的回答:

...
<script src="ShopListScript.js"></script>
</body>

最新更新