运行 Javascript 函数时遇到问题
Trouble getting a Javascript function to run
我对Javascript还很陌生,在让函数正常运行时遇到了一些麻烦。这是我所拥有的:
<script type='text/javascript'>
function GravityCalc (ratio, name)
{
Weight = getElementById('WeightBox').value * ratio;
document.getElementById('WeightText').innerHTML = 'You would weigh ' + weight + ' on ' + name;
}
</script>
Enter Weight: <input type='text' id='WeightBox' name='Weight'><br>
<button onclick='GravityCalc(2.3,Jupiter)'>calculate</button>
<div id='WeightText'> </div>
表单完美显示,但按下按钮时没有任何反应。可能还应该注意的是,最终,名称和比率参数将使用 PHP 进行解析。
你做错了几件事...
- "重量"应该是"重量"。 JS区分大小写,您在一行中以Camel大小写,在另一行中采用Pascal大小写。
- 您需要使用"document.getElementById"。 只是"getElementById"并不适用于所有浏览器。
- 您需要声明"权重"变量。
- 如果您愿意,dom 元素中的值存储为字符串或 char 数组,因此您需要将其解析为 int,如下所示,
parseInt(document.getElementById('WeightBox').value)
这是我的JSFiddle...http://jsfiddle.net/EH5j6/
function GravityCalc (ratio, name)
{
var weight;
weight = parseInt(document.getElementById('WeightBox').value) * ratio;
document.getElementById('WeightText').innerHTML = 'You would weigh ' + weight + ' on ' + name;
}
javascript 变量区分大小写!您的 Ws 不匹配。我还强烈建议使用 var
来显式声明您的变量。
var weight = getElementById('WeightBox').value * ratio;
document.getElementById('WeightText').innerHTML = 'You would weigh ' + weight + ' on ' + name;
另外,正如评论者所指出的,字符串必须用引号括起来。
<button onclick='GravityCalc(2.3,"Jupiter")'>calculate</button>
确保在
html 页面的头部包含 javascript。
function calc (ratio, name) {
var weight = document.getElementById('WeightBox').value * ratio;
document.getElementById('WeightText').innerHTML = "You would weigh " + weight + " on " + name;
}
并将 HTML 更改为:
Enter Weight: <input type='text' id='WeightBox' name='Weight'><br>
<button onclick="calc(2.3, 'Jupiter')">calculate</button>
<div id='WeightText'> </div>
相关文章:
- 将PHP变量传递给jQuery时遇到问题
- 将jQuery转换为用户脚本的普通Javascript时遇到问题
- 将子文档推送到父数组时遇到问题
- JQuery FullCalendar在从ajax成功调用rerenderEvents时遇到问题
- 在将javascript附加到我的html中时遇到问题
- 为什么我在以编程方式打开窗口时遇到问题
- 在将缩略图链接到模态时遇到问题
- 使用 ng 模型获取数据时遇到问题
- 是否有其他人在设计Twitter Typeahead时遇到问题'的搜索栏
- 使用jquery进行整数比较时遇到问题
- 使用PhantomJS下载动态web内容时遇到问题
- 设置RequireJS时遇到问题
- 让Javascript在SharePoint 2010上运行时遇到问题
- I'我在react.js中编写for循环时遇到问题
- 通过jQuery获取上传的文件名时遇到问题
- 我在启动我的节点时遇到问题.js IRC 机器人
- Ruby on Rails 4:在 Rails Web 应用程序中添加 Javascript 文件时遇到问题
- 从谷歌地图自定义控件打开离子模态时遇到问题
- 在使用 YAML 和 Google App Engine 时遇到问题
- 在 Chrome 扩展程序中将鼠标悬停在广告上使用时遇到问题