javascript实现的平方米、亩、公顷单位换算小程序
javascript实现平方米,亩,公顷单位换算,可以通过url传递参数指定输入框的值为任何中单位的值。
源代码如下:
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<title>javascript实现的平方米、亩、公顷单位换算小程序</title>
</head>
<body>
<selectonchange="selectChange(this)"id="sel">
<optionvalue="公顷">公顷</option>
<optionvalue="亩">亩</option>
<optionvalue="平方米">平方米</option>
</select>
这个input的值可能是3公顷、3亩、3平方米
<inputtype="text"value="3"id="input0"/>
<scripttype="text/javascript">
vara=parseInt('0');/////这里改为你动态接受到的值,0代表单位为平方米,1为亩,2为公顷
varsel=document.getElementById('sel');
sel.selectedIndex=2-a;/////设置单位下拉
varlastUnit=document.getElementById('sel').value;//记录当前单位
varinput=document.getElementById("input0");
//10000平米=15亩=1公顷
varfRate={//换算率
公顷:{亩:15,平方米:10000},
亩:{平方米:10000/15,公顷:1/15},
平方米:{亩:15/10000,公顷:1/10000}
};
functionselectChange(obj){//单位改变,执行换算
varv=parseFloat(input.value);//得到原来的值
//执行换算,注意fRate的取值,得到上一次的单位节点,再取当前单位的换算率
varrst=(v*fRate[lastUnit][sel.value]).toFixed(4);//保留4位小数
input.value=rst;
lastUnit=sel.value;//更新当前单位变量
}
</script>
</body>
</html>