简体   繁体   中英

JavaScript: Combining functions and scripts and buttons

I am going through the SAMS Learn JavaScript in 24 hours book. 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...

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.

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.

HERE'S WHAT I HAVE...(minus the headers, titles and HTML tags)

    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)"> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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