我正在使用下面的JavaScript检索某些输入元素的值。有两个输入元素;如果我在两者中输入值并按下按钮以使用/显示值,则只有第二个元素具有值。无论输入什么,第一个元素都保持值undefined。我尝试使用/显示此值的方式很多,似乎只是未定义。看看代码:
<!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>
答案 0 :(得分:1)
这是因为您调用了变量name
此name
实际上是指window.name
(窗口名称)。
如果您将变量重命名为stk
之类的其他内容,则可以使用:
var stk = document.getElementById("stk");
portfolio[stk.value] = qty.value;