简体   繁体   English

JavaScript:结合函数,脚本和按钮

[英]JavaScript: Combining functions and scripts and buttons

I am going through the SAMS Learn JavaScript in 24 hours book. 我正在通过SAMS在24小时内学习JavaScript。 The end of lesson three has an extra exercise to combine a Celsius to Fahrenheit from Lesson 2, with functions and buttons from Lesson 3. I was able to successfully complete the Try It exercises in Lessons 2 and 3... 第三课的末尾有一个额外的练习,将第2课中的摄氏到华氏度与第3课中的功能和按钮结合在一起。我能够成功完成第2课和第3课中的Try It练习。

LESSON 2 第二课

<!DOCTYPE html>
<html>
<head>
    <title>Fahrenheit From Celsius</title>
</head>
<body>
    <script>
    var cTemp = 100; // temperature in Celsius
    var hTemp = ((cTemp * 9) /5 ) + 32;
    document.write("Temperature in Celsius: " + cTemp + " degrees<br/>");
    document.write("Temperature in Fahrenheit: " + hTemp + " degrees");
</script>

LESSON 3 第三课

<!DOCTYPE html>
<html>
<head>
<title>Calling Functions</title>
<script>
    function buttonReport(buttonId, buttonName, buttonValue) {
        var userMessage1 = "Button id: " + buttonId + "\n";
        var userMessage2 = "Button name: " + buttonName + "\n";
        var userMessage3 = "Button value: " + buttonValue;
        alert(userMessage1 + userMessage2 + userMessage3);
    }
</script>

But I am stuck combining the two. 但是我坚持将两者结合。

EXERCISE TO COMBINE THE TWO: 锻炼结合两个:

Write a function to take a temperature value in Celsius as an argument and return the equivalent temperature in Fahrenheit, basing it on the code from Lesson 2. 根据第2课的代码,编写一个函数,以摄氏温度值作为参数,并以华氏温度返回等效温度。

Test your function in an HTML page having three buttons that, when clicked, pass values of 10, 20, and 30 degrees Celsius, respectively, to the function. 在具有三个按钮的HTML页面中测试您的功能,单击三个按钮后,分别将10,20和30摄氏度的值传递给该功能。

HERE'S WHAT I HAVE...(minus the headers, titles and HTML tags) 这是我所拥有的...(减去标题,标题和HTML标记)

    function temp(10, 20, 30) {
        var hTemp1 = ((temp * 9) /5 ) + 32;
        var hTemp2 = ((temp * 9) /5 ) + 32;
        var hTemp3 = ((temp * 9) /5 ) + 32;
        alert(hTemp1, hTemp2, hTemp3);
    }
</script>

</head>
<body>
<input type="button" value="10 X Celsius" onclick = hTemp1>
<input type="button" value="20 X Celsius" onclick = hTemp2>
<input type="button" value="30 X Celsius" onclick = hTemp3>

Can you please help me? 你能帮我么?

There's definitely better ways to do this. 肯定有更好的方法可以做到这一点。 But here's a solution for the purpose of this lesson. 但这是本课目的的解决方案。 I tried not to change too much of your code. 我试图不更改太多代码。 Check out the snippet below. 查看下面的代码段。

 function toF(cTmp) { return cTmp * 9 / 5 + 32 } function alertF(tmp) { alert(toF(tmp)) } 
 <input type="button" value="10" onclick="alertF(10)"> <input type="button" value="20" onclick="alertF(20)"> <input type="button" value="30" onclick="alertF(30)"> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM