gpt4 book ai didi

javascript - innerHTML 和访问对象属性

转载 作者:行者123 更新时间:2023-12-01 02:47:51 24 4
gpt4 key购买 nike

我想获取列表id的值。然后访问对象属性。例如,如果选择鸡蛋:我想要得到 Egg.cost(是 9)

但是,它显示为未定义。

HTML 部分:

<select id = "list">
<option value = "egg">Eggs</option>
<option value ="banana">Banana</option>
</select>

</select>
<button onclick ="getSelectValue()"></button>
<div id ="example">testing</div>

JavaScript:

function getSelectValue(){
var selectedValue = document.getElementById("list").value;
document.getElementById("example").innerHTML=selectedValue["cost"];
}

var banana = {
cost:1.39,
servings:6,
servingSize:1,
costPerServing:.23
};

var egg = {
cost:9,
servings:24,
servingSize:1,
costPerServing:.38

};

最佳答案

创建对象字典( items ),并使用 <select> 的值获取相关对象:

var list = document.getElementById("list");
var example = document.getElementById("example");
var items = {
banana: {
cost: 1.39,
servings: 6,
servingSize: 1,
costPerServing: .23
},

egg: {
cost: 9,
servings: 24,
servingSize: 1,
costPerServing: .38

}
};

function getSelectValue() {
var selectedValue = list.value;
example.innerHTML = items[selectedValue].cost;
}
<select id="list">
<option value = "egg">Eggs</option>
<option value ="banana">Banana</option>
</select>

<button onclick="getSelectValue()">Get cost</button>
<div id="example">testing</div>

关于javascript - innerHTML 和访问对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47146576/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com