您可以尝试这样的事情,您必须对容量下拉列表的容量值进行硬编码,但由于您无法更改该下拉列表,我认为这是最省钱的方法。除非您想解析文本并计算值(假设所有文本值都具有可以解析为最小值和最大值的值)。在这种情况下,您可以根据一组为给定文本字符串提供最小最大值的规则动态创建 myApp.capacityDropdownValues。
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<title>Example</title>
</head>
<body>
<select id="selContainers" onChange="myApp.setCap(this);">
<option value="can" data-capacity="0.33">Can</option>
<option value="1l" data-capacity="1">One liter bottle</option>
<option value="2l" data-capacity="2">Two liter bottle</option>
<option value="bathTub" data-capacity="500">Bath tub</option>
</select>
<select id="cap">
<option>> 500ml</option>
<option>500ml - 1l</option>
<option>1l - 2l</option>
<option>< 2l</option>
</select>
<script type="text/javascript">
var myApp = {};
// this part can go in a seperate js file
myApp.capacityDropdownValues=[
{min:0,max:0.5},
{min:0.5,max:1},
{min:1,max:2},
{min:2,max:1/0}
];
// sorry for using inline event binding, if you have
// code that can attach/add event listeners that supports multiple browsers
// I'd advice not to use inline binding.
myApp.setCap = function (el){
var op=el.options[el.selectedIndex],
capacity=parseFloat(op.getAttribute("data-capacity")),
i,caps=document.getElementById("cap");
for(i=0;i<myApp.capacityDropdownValues.length;i++){
if(myApp.capacityDropdownValues[i].min<=capacity &&
myApp.capacityDropdownValues[i].max>=capacity){
caps.selectedIndex=i;
return;
}
}
console.log("failed");
}
// set the values on load:
myApp.setCap(document.getElementById("selContainers"));
</script>
</body>
</html>
这是一些可以为您动态设置容量对象的示例代码,如果一个页面上有多个容量下拉列表,它会将容量对象设置为选择元素的属性。请注意,包含 > 的值不会很好地转换,因为 option.value 转换为 > 5,因此您可能必须在其上使用正则表达式以确保包含 > 和 < 字符 int 其值的选项被正确转换。
var myApp = {};
//translations for string to min max values
// if you have values in gallons you can correctly translate that to liters here
myApp.capStringToCapacity={
'0-500':{min:0,max:0.5},
'500ml - 1l':{min:0.5,max:1},
'1l - 2l':{min:1,max:2},
'2 and up':{min:2,max:1/0}
}
// adds min max values for each option to capacity select
myApp.init=function(){
var i,j,tmp=[];
for(i=0;i<myApp.containers.length;i++){
for(j=0;j<myApp.containers[i].options.length;j++){
tmp.push(myApp.capStringToCapacity[
myApp.containers[i].options[j].value]);
}
//just add the JS object as property to the select
myApp.containers[i].capacities=tmp;
}
}
// set capacity dropdowns to intitialise
myApp.containers=[document.getElementById("cap")];
myApp.init();