是否可以在数组引用中回显变量值

时间:2016-11-07 18:34:57

标签: javascript arrays

我需要按类拉出输入的值,然后" echo"或在关联数组中引用该值

到目前为止,我的javascript看起来像:

var phone_code = document.getElementsByClassName( 'model' ).value;
var phone = [];
phone["6s"] = "23.52";
phone["5s"] = "9.88";
phone["5Se"] = "14.59";
phone["7"] = "28.49";
phone["s7e"] = "27.49";
phone["s7"] = "23.52";
phone["s6e"] = "21.04";
phone["s6"] = "18.56";
phone["a5"] = "12.61";
phone["j5"] = "7.65";
phone["a3"] = "8.64";
phone["j3"] = "5.17";
phone["p9"] = "16.08";
phone["p9lite"] = "8.64";

document.getElementById("phone-cost").innerHTML = phone[phone_code]

数组输出为:

Your Phone would cost you £<span id="phone-cost"></span> per month

然而,输出只是读取&#34; undefined&#34;所以我不确定javascript是不是问题,或者我需要进一步了解这个过程

phone_code需要使用类,因为它从表单启用/禁用的下拉列表中拉出,无论启用哪个下拉列表都需要使用。我认为我的问题是

phone[phone_code]

我不应该如何引用变量,但我无法以正确的方式在数组中找到特定的答案

由于

1 个答案:

答案 0 :(得分:1)

两件事:

(1).getElementsByClassName()返回一个类似数组的元素对象,而不是单个元素 (2)虽然可以像在代码中那样使用数组,但使用普通对象要好得多。

见下文:

var btn = document.getElementById('getPrice');

btn.addEventListener('click', function() {
  var phone_code = document.getElementsByClassName('model')[0].value;

  var phone = {};
  phone["6s"] = "23.52";
  phone["5s"] = "9.88";
  phone["5Se"] = "14.59";
  phone["7"] = "28.49";
  phone["s7e"] = "27.49";
  phone["s7"] = "23.52";
  phone["s6e"] = "21.04";
  phone["s6"] = "18.56";
  phone["a5"] = "12.61";
  phone["j5"] = "7.65";
  phone["a3"] = "8.64";
  phone["j3"] = "5.17";
  phone["p9"] = "16.08";
  phone["p9lite"] = "8.64";

  document.getElementById("phone-cost").innerHTML = phone[phone_code];
});
<select class="model">
  <option value="6s">6s</option>
  <option value="5s">5s</option>
  <option value="5Se">5Se</option>
</select>
<input type="button" value="Get Price" id="getPrice" />Your Phone would cost you £<span id="phone-cost"></span> per month