是的,我在 3 个下拉框中有值,并且还会有更多(考虑添加大约 20 个下拉框,这些下拉框添加后会给出该商品的最终价格。这是 HTML 代码。
<form id="myform1>
<p>Testing 1</p>
<select id="Test1">
<option value="24">Item one</option>
<option value="29">Item Two<option>
<!--I have the first box going to 20 items-->
</select>
<p>Testing 2</p>
<select id="Test2">
<option value="25">Item one</option>
<option value="100">Item Two<option>
<!--I have the second box going to 10 items-->
</select>
<p>Testing 3</p>
<select id="Test3">
<option value="24">Item one</option>
<option value="100">Item Two<option>
<!--I have the third box going to 10 items-->
</select>
</form>
<button onclick="myFunction()">Update</button>
<p id="demo"></p>
然后我就有了我的Javascript
function myFunction()
{
var a = document.getElementById("list1");
var A = a.options[a.selectedIndex].value;
var b = document.getElementById("list2");
var B = b.options[a.selectedIndex].value;
var c = document.getElementById("list3");
var C = c.options[a.selectedIndex].value;
var IntA = parseInt(A);
var IntB = parseInt(B);
var IntC = parseInt(C);
var x=IntB + IntA;
var y=x + IntC;
var demoP=document.getElementById("demo")
demoP.innerHTML= y;
}
我的问题是,只有当我完全采用 var c 然后取出 var y 并让它计算为 x 时,它才有效。我尝试了很多方法,却束手无策。干杯
附注Java 脚本位于底部的 script 标签中
最佳答案
您已使用a.selectedIndex
获取所有三个元素的选定项目。将其更改为使用 b.selectedIndex
和c.selectedIndex
在适当的地点。或者你可以直接说a.value
, b.value
和c.value
直接而不是通过 options
收藏。
此外,html 中的 id 属性与您在 JS 中使用的属性不匹配。
解决这些问题并且它可以工作,正如您在此处看到的:http://jsfiddle.net/6WWdc/
附注养成始终将基数作为第二个参数传递给 parseInt()
的习惯是个好主意。 ,例如IntA = parseInt(A, 10);
- 否则,如果输入字符串具有前导 0
或领先0x
它可能(取决于浏览器和 "use strict";
指令的存在)被解释为八进制或十六进制。
关于Javascript 无法将变量添加到一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14820777/