iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 7
0
自我挑戰組

JavaScript 新手筆記系列 第 7

Day07 - 變數(04)

前言

今次把 BMI 的計算結果,直接顯示在網頁上

程式

index.html

<body>
 <p>小明的體重為 <em id="weight"></em> 公斤</p>
 <p>身高為 <em id="height"></em> 公分</p>
 <p>BMI 計算的結果為:<em id="BMI"></em></p>
 <p>判斷為:<em id="ans"></em></p>
 <script src="JS/test.js"></script>
</body>
  • 輸入以上程式碼
  • 把想要顯示的使用 <em> 表示,並設定相關 id
    • 體重:id="weight"
    • 身高:id="height"
    • BMI:id="BMI"
    • 判斷:id="ans"
  • src="JS/test.js"讀取 JS 資料夾內的 test.js 檔案

test.js

var weight = 60;  // 重量
var height = 1.70; // 身高(公尺)
var BMI = weight / (height * height);
var ans;
console.log("BMI值:" + BMI); // 印出結果

if (BMI >= 18 && BMI <= 24){
    ans = ("似乎還蠻正常的!");
    console.log(ans);
    } else if (BMI > 24){ 
        ans = ("似乎有點過胖囉!");
        console.log(ans);
    } else { 
        ans = ("似乎有點過瘦囉!");
        console.log(ans);
    }

document.getElementById('weight').textContent = weight;
document.getElementById('height').textContent = height * 100; // 公分
document.getElementById('BMI').textContent = BMI;
document.getElementById('ans').textContent = ans;
  • 輸入以上程式碼,內容與判斷同前一天的方法
  • 新增使用 document.getElementById( ).textContent 進行各變數的轉換
    • document.getElementById('weight').textContent = weight; 為例
    • document:取得 HTML 文件
    • getElementById('weight'):在 HTML 文件中透過 id 來找'weight'的元素
    • textContent:取得這個元素的文字內容
    • = weight:把內容設定成變數 weight 的值

執行結果

補充

  • 小數點太多

    • 使用 toFixed(小數位數),不過處理過的數字會變字串(使用 typeof 查)
    var a = 3.1415;
    console.log(a.toFixed(2)); // 小數2位,顯示3.14
    console.log(typeof a); // 為 number
    
    var a1 = a.toFixed(2);
    console.log(a1); // 小數2位,顯示3.14
    console.log(typeof a1); // 為 string
    
    • 將小數變整數後再除回來,但測試結果沒變化
    var b = 3.1415;
    console.log((b * 100) / 100 ); // 測試顯示3.1415
    console.log(typeof b);  // 為 number
    
    
    • 暫時還不知道一般使用哪種,提供參考,未來有看到說明再修正
    • 因此 BMI 顯示可以修改如下
    document.getElementById('BMI').textContent = BMI.toFixed(2);
    // 顯示小數2位為20.76
    
  • 試試看把 index.html 裡的 <script src="JS/test.js"></script>移到<body>的最上面看看

    • 應該會發現那些數字都沒有顯示!
    • 那是因為後來才讀到 HTML 的那些字,被蓋過去了

次回

接下來就進入函數的部分吧!


上一篇
Day06 - 變數(03) - BMI
下一篇
Day08 - 函數(01)
系列文
JavaScript 新手筆記31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言