你可以嘗試這樣的東西,你將不得不硬編碼容量下拉的容量值,但既然你不能改變那個下拉,我認爲這是一個最好的方式。除非你想解析文本並計算值(假設所有文本值的值都可以解析爲最小值和最大值)。在這種情況下,您可以根據一組規則爲給定文本字符串動態創建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