简体   繁体   English

根据下拉字段的值选择对象的值

[英]Selecting value of an object based on value of dropdown field

Codepen: https://codepen.io/moarpie/pen/EBKVBL Codepen: https ://codepen.io/moarpie/pen/EBKVBL

I'm trying to do two things in this project: 我正在尝试在此项目中做两件事:

  • Display text based on selector value 根据选择器值显示文本
  • Get value from input field and modify by value of an object based on selection from dropdown 从输入字段获取值,并根据下拉菜单中的选择按对象的值进行修改

The first part I have accomplished, but I am having trouble getting the second part to work. 我已经完成了第一部分,但是我很难让第二部分开始工作。

Example: If bear is selected from dropdown, I want to output bear.weight and if puma is selected I want to output puma.weight . 示例:如果从下拉列表中选择bear ,则我要输出bear.weight ;如果选择了puma则要输出puma.weight

So instead of 所以代替

var outputValue = (parseInt(userInput) / parseInt(puma.weight)) * 100;

The parseInt( puma .weight) should should be whatever value is selected in the dropdown. parseInt( puma .weight)应该是下拉菜单中选择的任何值。

I've gotten this to work by just using if statements but of course this isn't best practice and becomes tedious if I have 100 objects to choose from. 我已经通过仅使用if语句来使它起作用,但这当然不是最佳实践,如果我有100个对象可供选择,这将变得很乏味。

Inside the click event callBack function, you can get a string from the currently selected option using 在click事件callBack函数中,您可以使用以下命令从当前选择的选项中获取字符串

var selectedAnimal = document.getElementById('animalSelector').value;

This will return eg puma 这将返回例如彪马

To get the weight value from it's associated object (var puma = {name:"pumaName", weight:500};) you can use 要从其关联对象(var puma = {name:“ pumaName”,weight:500};)中获取权重值,可以使用

eval(selectedAnimal).weight

So for example 所以举个例子

var outputValue = (parseInt(userInput) / parseInt(eval(selectedAnimal).weight)) * 100;

you can create an object with name of weight and define the value for all dropdown value like if you have value in dropdown 您可以创建一个名称为weight的对象,并为所有下拉菜单值定义值,例如下拉菜单中是否有值

<select id="animal">
<option value="bear">bear</option>
<option value="puma">puma</option>
</select>

then object must be like weight = {'bear': 150, 'puma': 200}; 然后物体必须像weight = {'bear': 150, 'puma': 200}; now suppose you get puma from your dropdown then 现在假设您从下拉菜单中得到了彪马

let output = parseInt(userInput) /parseInt(weight[document.querySelector( "#animal option:selected" ).value]) * 100

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM