我对javascript知之甚少 [英] I know very little about javascript
问题描述
在VB中,您可以选择一个case语句,例如:
In VB, you can have a select case statement such as:
Dim x, y as string
select case x
case "1"
select case y
case "A"
return "1"
case "B"
return "2"
end select
Select case y
case "C"
return "3"
case "D"
return "4"
end select
case "2"
select case y
case "A"
return "5"
case "B"
return "6"
end select
Select case y
case "C"
return "7"
case "D"
return "8"
end select
end select
我一直试图弄清楚如何用javascript做这件事,但我运气不好。
I've been attempting to figure out how to do this with javascript, but I'm not having much luck.
function myFuels()
{
var x;
var tp = document.getElementsByName("fType").item(0);
var ld = document.getElementsByName("loading").item(0);
switch (tp)
{
case "Item 1":
switch (ld):
{
case "Low":
x="3.0";
break;
case "Moderate":
x="4.0";
break;
case "Heavy":
x="4.4";
break;
}
break;
case "Item 2":
switch(ld):
{
case "Low":
x="2.6";
break;
case "Moderate":
x="3.8";
break;
case "Heavy":
x="5.1";
break;
}
break;
document.getElementById("tonsavailable").innerHTML=x;
}
我甚至不确定我的变量格式是否正确以获取数据来自用户输入表单:ftype和loading元素是DropDown框,预先填充表单上的选择。所以我的最终结果应该基于这两个选项。
I'm not even sure if my variables are in the correct format to get the data from the users input form: The "ftype" and "loading" elements are DropDown boxes that are pre-filled with selections on the form. So my end result should be based off of Both of those selections.
推荐答案
结构是正确的;但是,这里缺少的谜题不在switch语句中,而是在你正在使用的数据中。
The structure is correct; however, the missing puzzle here is not in the switch statement, but in the data you are using.
// Returns an actual DOM element
var tp = document.getElementsByName("fType").item(0);
var ld = document.getElementsByName("loading").item(0);
if(tp){// check if not null
switch(tp.id){
// Continue as usual
}
}
不使用switch语句中的DOM元素,而是使用元素的id或其他属性。在
Instead of using the DOM element in the switch statement, use the id of the element, or another attribute. Use same logic on
ld
<html>
<head>
<script type="text/javascript">
function getData(){
var a = document.getElementById("1").value;
alert(a);
switch(a){
case 1:
alert(a+"---->1");
break;
case 2:
alert(a+"---->2");
break;
case 3:
alert(a+"---->3");
break;
default:
alert("Def");
break;
}
}
</script>
</head>
<body>
<h1>
<input type ="text" id="1"
<button type="button" onclick="getData()">Difference</button>
<p id="demo" style="vertical-align: top">
</p>
</body>
</html>
这篇关于我对javascript知之甚少的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!