你可以尝试这样的东西,你将不得不硬编码容量下拉的容量值,但既然你不能改变那个下拉,我认为这是一个最好的方式。除非你想解析文本并计算值(假设所有文本值的值都可以解析为最小值和最大值)。在这种情况下,您可以根据一组规则为给定文本字符串动态创建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>
这里是可以动态地设置对象的能力为你的情况下有一个页面上的多个容量下拉列表,它会设置对象的能力作为选择元素的属性一些示例代码。请注意,包含& gt的值不会很好地转换,因为option.value转换为> 5,因此您可能必须使用正则表达式来确保包含>和<个字符的选项在其值中被正确转换。
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();
来源
2013-05-17 05:07:41
HMR
我还没有这样做过,但一个好方法是将数据容量添加到您的选项元素。由于您不打算重新设计生成选择html的控件,因此您可以在选项值上使用正则表达式,看起来像获取第一个数字将会执行的操作。 – HMR
为什么是Java标记?这与Java有什么关系? –
这是支持它的模型;但公平的电话,我会删除标签...编辑:或不,因为这太小编辑问题。 – f1dave