1

我是 javaScript 的新手,我试图让一个函数在我在 HTML 文件中创建的按钮单击时运行。我希望函数将值返回到 html 文件中的段落标记。

现在,这是我第一次尝试这个,我不知道如何将参数从文本框传递到脚本的函数中,并将值打印到段落标签。有人可以告诉我如何,请。

谢谢

<script>
var calculateTotalCosts = function(salary,numWorkers,city)
    {
        fixedCosts = 5000;
        variableCosts = salary*numWorkers;
        switch(city)
        {
            case "BEJ":
                rent = 25000;
                break;
            case "NYC":
                rent = 30000;
                break;
            default:
                rent = 10000;
                break;
        }
        return rent + variableCosts + fixedCosts;
    };
</script>
Salary: <input type="text" value="Costs" />
No. Workers: <input type="text" value="Num of Workers" />
City: <input type="text" value="City" /><br />
<button onclick="calculateTotalCosts()"type="button">Calculate</button>
<p id="displayCost"></p>
4

2 回答 2

1

您可以获取元素值并在函数中计算它们并将其传递给 p html elemnet

 <script>

    function CalculateCosts() {
        var costsVal = document.getElementById("costs").value;
        var workersVal = document.getElementById("workers").value;
        var cityVal = document.getElementById("city").value;
        calculateTotalCosts(costsVal, workersVal, cityVal);
    }

    var calculateTotalCosts = function (costsVal, workersVal, cityVal) {

        var variableCosts = costsVal * workersVal;
        var rent;
        switch (cityVal) {
        case "BEJ":
            rent = 25000;
            break;
        case "NYC":
            rent = 30000;
            break;
        default:
            rent = 10000;
            break;
        }
        //return rent + variableCosts + fixedCosts;
        document.getElementById("displayCost").innerHTML = rent + variableCosts;
    };

</script>
Salary:
<input id="costs" type="text" placeholder="Costs" />
No. Workers:
<input id="workers" type="text" placeholder="Num of Workers" />
City:
<input id="city" type="text" placeholder="City" /><br />
<button onclick="CalculateCosts()" type="button">
    Calculate</button>
<p id="displayCost">
</p>
于 2013-03-29T21:11:45.327 回答
0

您必须提供输入 id 或知道哪些输入指向什么。见下文:

 <script>
  function calculateTotalCosts()
     {
        input_text = document.getElementsByTagName("input");
        salary = input[0];
        numWorkers = input[1];
        city = input[2];

        fixedCosts = 5000;
        variableCosts = salary*numWorkers;
        intcity = 0;
        if (city == "BEJ") { intCity = 0;}
        if (city == "NYC") { intCIty = 1;}
        switch(intCity)
        {
            case 0:
               rent = 25000;
               break;
            case 1:
               rent = 30000;
               break;
            default:
               rent = 10000;
               break;
    }
    result = rent + variableCosts + fixedCosts;
    document.getElementById("displayCost").innerHtml = result;
}
</script>

或使用 ids 进行输入,这样您就可以确定您选择的是哪个输入。

于 2013-03-29T21:12:55.177 回答