【发布时间】:2021-06-11 01:34:40
【问题描述】:
我正在尝试使用表单来使用 JS 创建对象,然后获取这些对象属性并将它们添加到页面上的表格中。这是我想出的,但我不明白为什么它会这样。它像想要添加一些东西一样闪烁,但没有更多。
HTML
<form>
<fieldset>
<legend>Enter the item name.</legend>
<input type="text" id="name" /> </fieldset>
<fieldset>
<legend>Enter the quantity of units needed.</legend>
<input type="number" id="amount" /> </fieldset>
<fieldset>
<legend>Enter the name of the store to buy this from.</legend>
<input type="text" id="store" /> </fieldset>
<button onclick="add()">Add Item</button>
</form>
JavaScript
//global variable
var myItem;
//custom object constructor
function Item(name, amount, store) {
this.itemName = name;
this.itemAmount = amount;
this.itemStore = store
}
function add() {
var itemName = document.getElementById("name").value;
var itemAmount = document.getElementById("amount").value;
var itemStore = document.getElementById("store").value;
//creates a new item object and stores it
myItem = new Item(itemName, itemAmount, itemStore);
// Find a <table> element with id="list":
var table = document.getElementById("list");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(0);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
// Add some text to the new cells:
cell1.innerHTML = "y";
cell2.innerHTML = "y";
cell3.innerHTML = "y";
}
【问题讨论】:
标签: javascript forms object constructor