如何根据已选择的选项获取对象?

时间:2017-10-25 15:06:29

标签: javascript object javascript-objects options

这里有代码:



var i4options = {
  TTXT1: [
  {val: "01", id: "(01) XT1 Option 1"},
  {val: "02", id: "(02) XT1 Option 2"}
  ],
  TTXT2: [
  {val: "01", id: "(01) XT2 Option 1"},
  {val: "02", id: "(02) XT2 Option 2"}
  ]
};

function i4check() {
  const i1checkval = i1.options[i1.selectedIndex].value;
  const i2checkval = i2.options[i2.selectedIndex].value;
  const i3checkval = i3.options[i3.selectedIndex].value;
  const i4checkoutput1 = "i4options" + i1checkval + i2checkval + i3checkval;

  let userSettings = {
    'product': i1checkval,
    'type': i2checkval,
    'source': i3checkval,
  };

  if (userSettings.product !== '---' && userSettings.type !== '---' && userSettings.source !== '---') {
    let newItem = document.createElement('option');

    var nofentries = i4options.(i1checkval + i2checkval + i3checkval).length;
    var x = 0;
    while (x < nofentries){
      i4.appendChild(new Option(i4options.(i1checkval + i2checkval + i3checkval)[x].id, i4options.(i1checkval + i2checkval + i3checkval)[x].val));
      x += 1;
    }
		
  }
}

function generatordropdown(){
  var o1 = i1.options[i1.selectedIndex].value;
  var o2 = i2.options[i2.selectedIndex].value;
  var o3 = i3.options[i3.selectedIndex].value;
  var o4 = i4.options[i4.selectedIndex].value;
	
  var output = o1 + o2 + o3 + o4;
	
  document.getElementById("output").value = output;
}
&#13;
<form action="database/additem.php" method="post">

<h1>product</h1>
<select id="i1" onchange="generatordropdown(); i4check();" name="product">
  <option selected="true" disabled="disabled">---</option>
  <option value="T">(T) Telephone</option>
</select><br>

<h1>type</h1>
<select id="i2" onchange="generatordropdown(); i4check();" name="type">
  <option selected="true" disabled="disabled">---</option>
  <option value="T">(T) Model T</option>
</select><br>

<h1>source</h1>
<select id="i3" onchange="generatordropdown(); i4check();" name="source">
  <option selected="true" disabled="disabled">---</option>
  <option value="XT1">(XT1) XT1</option>
  <option value="XT2">(XT2) XT2</option>
</select><br>

<h1>i4</h1>
<select id="i4" onchange="generatordropdown()" name="category">
  <option selected="true" disabled="disabled">---</option>
</select><br>

<h1>ID</h1>
<input onClick="this.setSelectionRange(0, this.value.length)" type="text" id="output" name="id" style="width: 50%;" readonly><br>

</form>
&#13;
&#13;
&#13;

或者如果您更喜欢jsfiddle:https://jsfiddle.net/2kd6LdLc/

在第27和30行,它说:

(i1checkval + i2checkval + i3checkval)

如果选项i3是XT1,我在这里尝试做的是检查TTXT1,如果选项i3是XT2,则检查TTXT2。我可以使用if语句执行此操作,但是如果必须的话,我想轻松添加新对象,所以我不想每次都添加一个if语句。有关如何做到这一点的任何建议?我可以使用eval(),如果它是唯一的方法,但我不知道如何使用它。

1 个答案:

答案 0 :(得分:2)

您只需使用方括号按属性名称索引对象:

var entries = i4options[i1checkval + i2checkval + i3checkval];
var nofentries = entries.length;
var x = 0;
while (x < nofentries){
  i4.appendChild(new Option(entries[x].id, entries[x].val));
  x += 1;
}