使用 JavaScript 的输入元素的未定义值

value of undefined for input element using JavaScript

我正在使用下面的 JavaScript 检索一些输入元素的值。有两个输入元素;如果我在两者中都输入值并按下按钮 use/display 值,则只有第二个元素有值。无论输入什么,第一个元素都保持未定义的值。我已经尝试 using/displaying 这个值的许多方法,它似乎只是未定义。查看代码:

<!DOCTYPE html>
<html>
<head>
    <title>Stock Portfolio</title>
</head>
<body>
    <table>
        <tr><th>Enter Stock Portfolio Data</th></tr>
        <tr><td>Name of stock:</td>
        <td><input id="stk"></td></tr>
        <tr><td>Amount of shares:</td>
        <td><input id="shares"></td></tr>
        <tr><th>Press button to add new stock to your portfolio:</th>
        <td><button onclick="addstock();">Add</button></td></tr>
        <tr><th>Press button to calculate value of your stocks:</th>
        <td><button onclick="getvalue();">Calculate</button></td></tr>
        <tr><td>Value of Stocks:</td>
        <td><span id="stockvalues"></span></td></tr>
    </table>
<!-- JavaScript code for stock portfolio -->
<script>
    //"use strict";

    // stock portfolio

    var portfolio = {}; // portfolio object

    var name   = document.getElementById("stk");
    var qty    = document.getElementById("shares");
    var values = document.getElementById("stockvalues");

    // function that adds stock properties and amount of shares to portfolio object
    function addstock() {
        // here's the code I want to use here
        // I've tried just displaying the value of name.value, but that is undefined
        // so the value will be the name for the object's properties
        portfolio[name.value] = qty.value;
    }

    //  function that gets the current price of stocks
    function getquote(stock) {
        // does nothing for now
    }

    // function that calculates value of shares in stocks and returns that value
    function displaystocks() {
        var result = []; // The array we will return

        for(var prop in portfolio) { // For all enumerable properties
            result.push(prop); // add it to the array.
        }
        values.innerHTML = result;
    }

    // function that calculates value of shares in stocks and returns that value
    function getvalue() {
        var total = 0;

        for(var stock in portfolio) { // For each stock in the portfolio:
            var numshares = portfolio[stock]; // get the number of shares
            var price = 10; // Could CALL FUNCTION -- getquote(stock);  look up share price

            total += numshares * price; // add stock value to total value
        }
        values.innerHTML = total;
    }
</script>
</body>
</html>

这是因为你调用了你的变量name
这个name实际上是指window.name(window的名字)。

如果您将变量重命名为 stk 之类的其他名称,它将起作用:

var stk = document.getElementById("stk");

portfolio[stk.value] = qty.value;