[英]value of undefined for input element using JavaScript
我在下面使用此JavaScript检索某些输入元素的值。 有两个输入元素; 如果我在两者中都输入了值并按下按钮以使用/显示值,则仅第二个元素具有值。 无论输入什么,第一个元素都将保持未定义的值。 我尝试过使用/显示此值的许多方式,它似乎只是未定义的。 查看代码:
<!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
(窗口的名称)。
如果将变量重命名为stk
其他名称,它将起作用:
var stk = document.getElementById("stk");
portfolio[stk.value] = qty.value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.