一个简单的Javascript函数无法正常工作(将华氏温度转换为摄氏温度)

时间:2016-05-14 20:41:52

标签: javascript function

当您点击“点击此处!”按钮时,我正试图这样做。出现以下句子:“温度为25摄氏度。”有人可以告诉我为什么我的代码无法运行,我该如何解决? 这是我的代码:

<p id="demo">This is my first paragraph</p>

<button type="button" onclick="toCelsius(fahrenheit)">Click Here!</button>

<script>
    function toCelsius(fahrenheit) {
        return (5/9) * (fahrenheit-32);
        document.getElementById("demo").innerHTML = "The temperature is " +  toCelsius(77) + " Celsius";
    }
</script>

3 个答案:

答案 0 :(得分:0)

你过早地放置了return语句(return语句总是结束函数的执行,因此显示温度的部分没有运行。)

return替换为var c=,并将toCelsius(77)替换为位于其下方的c

此外,您的按钮事件处理程序显示toCelsius(fahrenheit); fahrenheit未定义。如果您在网页上添加<input id='fahrenheit' placeholder='temperature' />,则可以将按钮的事件处理程序更改为toCelsius(document.getElementById('fahrenheit').value)

:)就像那样,你有一个计算器!

示例:

 <p id="demo">This is my first paragraph</p>

<input id='fahrenheit' placeholder='temperature' />
<button type="button" onclick="toCelsius(document.getElementById('fahrenheit').value)">Click Here!</button>

<script>
     function toCelsius(fahrenheit) {
     var celsius (5/9) * (fahrenheit-32);
     document.getElementById("demo").innerHTML = "The temperature is " +
          celsius + " Celsius";
     }
</script>

答案 1 :(得分:0)

试试这个。

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.github.sarxos.webcam.Webcam;

public class TakePictureExample {

public static void main(String[] args) throws IOException {

    // get default webcam and open it
    Webcam webcam = Webcam.getDefault();
    webcam.open();

    // get image
    BufferedImage image = webcam.getImage();

    // save image to PNG file
    ImageIO.write(image, "PNG", new File("test.png"));
}
}

你的代码不起作用,因为你在分配到innerHtml属性之前有一个返回语句

答案 2 :(得分:0)

使用此代码:

<script>
function toCelsius(fahrenheit) {
    return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = "The temperature is " +  toCelsius(77) + " Celsius";
</script>