Javascript 无法将变量添加到一起

标签 javascript html

是的,我在 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.selectedIndexc.selectedIndex在适当的地点。或者你可以直接说a.value , b.valuec.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/

相关文章:

javascript - MongoDB 简单时间序列

Javascript 行号映射

html - 如何将此 css 隔离到适当且唯一的类中,以便它们不会干扰其他页面布局

javascript - 设置 Gatsby 博客分层 URL slug 结构

html - 中心对齐图像列表

php - 尝试使用 PHP 创建注册表单

javascript - 如何为 Gmail、Hotmail 等电子邮件阅读器创建预览模式

javascript - 如何编写 Photoshop JavaScript 脚本将 PSD 文件中的所有图层复制到新文档?

javascript - 如何做 Modal Bootstrap 出现在底部

c# - 将文本框中的信息发布到不同解决方案中的另一个文本框