簡體   English   中英

用Javascript計算圓周和圓周面積-函數不起作用

[英]Calculating Circumference and Area of Circle With Javascript - Function Not Working

我正在嘗試創建一個簡單的JavaScript應用程序,該應用程序將要求用戶輸入圓的半徑,並在用戶點擊“計算”后以句子形式顯示圓周和面積。 現在,當用戶輸入數字並單擊“計算”時,什么也沒有發生。

JavaScript包含在HTML文檔中,如下所示:

<!DOCTYPE html>
<html>
<head>
  <meta charset = "utf-8">
  <title>Create a Circle</title>
  <h1 style="text-align:center">Create a Circle!</h1>
  <br>
  <div style="text-align:center">
  Enter the radius for your circle:
  <input type="text" id="txtRadius" size="10" />
  <br>
  <input type="button" value="Calculate" onclick="CalculateArea()"/>

  <script>

  function print() {
    var p = 
    document.createElement("p"),
    text = Array.prototype.join.call(arguments,",");
    p.textContent = text;
    document.getElementById("console").appendChild(p);
    return text;    
  }

  function CalculateCircumference() {
    var radius =
    parseInt(document.getElementById('txtRadius').value);//String to Integer

    if (0 < radius)
        print("The circumference of the circle is " + (radius * 2 * Math.PI);
    else
        print("Error - radius must be a whole number greater than 0.");
    return false;
  }

  function CalculateArea() {
    var radius = 
    parseInt(document.getElementById('txtRadius').value); //String to Integer

    if (0 < radius)
        print("The area of the circle is " + (radius * radius * Math.PI);
    else
        print("Error - radius must be a whole number greater than 0.");
    return false;
  }
</script>
</head>
<body>
</body>   
</html>

我是打印方法的新手,所以我嘗試將所有打印內容更改為“警報”,但是此操作無濟於事。 謝謝您的幫助。 鏈接到JSFiddle: https ://jsfiddle.net/HappyHands31/xzsf8ca4/2/

您的代碼有更多問題,但這將回答您的問題

什么都沒發生的原因是因為您缺少a )並使函數無效。

更改為: print("The area of the circle is " + (radius * radius * Math.PI);

為此: print("The area of the circle is " + (radius * radius * Math.PI));

參見小提琴https://jsfiddle.net/xzsf8ca4/4/

function CalculateCircumference() {
    var radius =
    parseInt(document.getElementById('txtRadius').value);//String to Integer

    if (radius > 0)
        //calculate
    else
        //error
    return false;
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM