将变量值从html表格传递到javascript
问题描述:
我似乎无法得到这个工作,我已经尝试了很多。我有一个jscript文件,其中包含一个很长的涉及函数,可以进行各种计算。我正在尝试为jscript文件中存在的变量传递值。 jscript文件包含3个变量,我希望能够从HTML表单页面进行更改。将变量值从html表格传递到javascript
我试图改变的jscript文件中的变量是vehicleWeight,轴距和tireChoice。请注意,jscript文件完美无瑕地工作,但我希望能够更改变量,而无需进入并手动说var vehicleWeight = 300等。我在framework.js中运行的函数是Main。
这就是我的HTML页面的样子。
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Page</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript" src="framework.js"></script>
<script type="text/javascript">
function ShowCalculation() {
Main($("#wheelBaseTxt").val(), $("#tireChoiceSel").val(), $("#wheelBaseTxt").val());
}
</script>
</head>
<body>
Vehicle Weight:
<input id="vehicleWeightTxt" type="text" /><br />
Tire Choice:
<select id="tireChoiceSel">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br />
Wheel Base: <input type="text" id="wheelBaseTxt" /><br />
<input type="submit" onclick="ShowCalculation(); return false;" />
</body>
</html>
答
很难说,没有查看您的JavaScript包括但您可能需要类似于您的Main
函数内的代码类似的东西。
var vehicleWeight = 0.0;
var wheelbase = 0.0;
var tireChoice = 0.0;
function Main(inpVehicleWeight, inpWheelbase, inpTireChoice) {
vehicleWeight = inpVehicleWeight;
wheelbase = inpWheelBase;
tireChoice = inpTireChoice;
// ... other calculations, etc ...
}
答
除非框架js中定义的变量是全局变量,否则您无法更改它们的值。
答
我这样做:
<script type="text/javascript">
function ShowCalculation() {
alert($("#wheelBaseTxt").val() + "; " + $("#tireChoiceSel").val() + "; " + $("#wheelBaseTxt").val());
}
</script>
...这似乎并没有与jQuery的一个问题...值的存在。 使用此方法进行测试。这个问题可能在Main()函数中。
发布'Main'代码和任何其他支持它的代码。 – lincolnk
这一切看起来都很棒。你的Javascript看起来像什么? – FishBasketGordo
不知道'Main',这是不可能诊断。 – cwallenpoole