innerHTML&访问对象属性

时间:2017-11-06 22:02:13

标签: javascript html innerhtml

我想获取列表ID的值。然后访问object属性。 例如,如果选择鸡蛋: 我想得到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

          };

2 个答案:

答案 0 :(得分:2)

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

&#13;
&#13;
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;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

那是因为selectedValue是字符串"egg",而不是变量egg。您需要将两个对象分组到另一个对象中(让我们称之为foods),如下所示:

var foods = {
  egg: {
    // …
  },
  banana: {
    // …
  }
}

然后,您可以按foods[selectedValue].cost提取值。