var stocks = [
['Apple',100,8998,723,7212],
['Microsoft',928,1992,821,2381]
];
var select = document.getElementById("selectStock");
for(var i = 0; i < stocks.length; i++) {
var opt = stocks[i][0];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
<select id="selectStock">
<option>Choose a stock</option>
</select>
我有多个Javascript数据数组(从Excel中提取),并且具有基本上基于数组行进行计算的不同函数。例如:
var stocks = [['Apple',100,8998,723,7212]['Microsoft,928,1992,821,2381]]
我需要做的是制作一个下拉菜单,允许用户选择一个选项(Microsoft或Apple),然后根据此选择,将此值拉入公式进行计算
document.write(Math.round(stocks[i][1] * 100)/100 + " dollars per share");
其中i是基于关闭下拉菜单选项的变量。这有意义吗?我不确定如何处理这个,这是个人项目。谢谢你的帮助!
答案 0 :(得分:1)
https://jsfiddle.net/b22y3v85/
var select = document.getElementById("selectStock");
select.onchange = (e) => {
let index = stocks.indexOf(stocks.find(a => a.indexOf(e.target.value) > -1));
document.write(Math.round(stocks[index][1] * 100)/100 + " dollars per share");
};
答案 1 :(得分:1)
这是一个工作示例,尽管您可能希望执行除document.write
之外的其他操作。
var stocks = [
['Apple',100,8998,723,7212],
['Microsoft',928,1992,821,2381]
];
var select = document.getElementById("selectStock");
for(var i = 0; i < stocks.length; i++) {
var opt = stocks[i][0];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
function getPrice(stock) {
var price = false;
for (var a = 0; a < stocks.length; a++) {
if (stocks[a][0] == stock) {
price = stocks[a][1];
break;
}
}
if (!price) { alert("Incorrect choice."); return; }
document.getElementById("result").innerText = stock + " is currently " + (Math.round(price * 100)/100 + " dollars per share");
}
<select id="selectStock" onchange="getPrice(this.value);">
<option>Choose a stock</option>
</select>
<br><br>
<div id="result"></div>
编辑:在页面上显示div
的结果,而不是使用document.write()
覆盖页面。
答案 2 :(得分:0)
<...>
private int playerHealth;
public bool isDead;
<...>
void Start ()
{
playerHealth = 3;
isDead = false;
}
<...>
public void SubLive()
{
playerHealth--;
UpdateLives ();
if (playerHealth <= 0)
{
isDead = true;
}
}
void UpdateLives ()
{
livesText.text = "Lives: " + playerHealth;
}