我仍然是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解析。
答案 0 :(得分:1)
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>
答案 1 :(得分:1)
确保在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>
答案 2 :(得分:1)
你有几件事情错了......
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;
}