【问题标题】:How to add object that is created with a button to a table?如何将使用按钮创建的对象添加到表中?
【发布时间】: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


    【解决方案1】:

    总是定义按钮类型属性,不同的浏览器对没有属性的按钮有不同的反应,即Firefox它的行为就像“提交”,所以在你的情况下它闪烁(重新加载)https://www.w3schools.com/tags/att_button_type.asp 所以在你的按钮行添加 type="button"

    <button type="button" onclick="add()">Add Item</button>
    

    【讨论】:

    • 小子我是不是觉得自己很傻,非常感谢!我意识到这也是为了显示创建的对象的属性,但这很容易修复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 2020-01-16
    相关资源
    最近更新 更多