运行 Javascript 函数时遇到问题

Trouble getting a Javascript function to run

本文关键字:遇到 问题 函数 Javascript 运行      更新时间:2023-09-26

我对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 进行解析。

你做错了几件事...

  1. "重量"应该是"重量"。 JS区分大小写,您在一行中以Camel大小写,在另一行中采用Pascal大小写。
  2. 您需要使用"document.getElementById"。 只是"getElementById"并不适用于所有浏览器。
  3. 您需要声明"权重"变量。
  4. 如果您愿意,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>