使用Javascript生成表

时间:2015-11-09 03:53:51

标签: javascript loops for-loop

我正在尝试根据我运行的两个循环生成一个表。

example of what I am trying to achieve

现在我只是想让表格生成,但不断收到此错误:

  

无法读取null的属性'appendChild'。

它所指的代码行是:

body.appendChild(tbl);

但我不确定为什么tbl无法正确追加。任何帮助将不胜感激。

var bmrMultiplier;
var userBMR;


function genderInput() {

  gender = prompt("Please enter your gender, note that answers are case sensitive and must be entered exactly as shown:\n\nF: for Female\nM: for Male\n");

  switch (gender) {
    case "M":
      console.log('Gender is ' + gender);
      bmrMultiplier = 26.4;
      weightInput();
      break;
    case "F":
      console.log('Gender is ' + gender);
      bmrMultiplier = 24.2;
      weightInput();
      break;
    default:
      alert('That is not a proper selection.');
      document.write('Please refresh the page to try again');
      console.log('default');
  }
}

//Sets up second user prompt and sets the value of difficulty based on the user selection

function weightInput() {

  weight = parseInt(prompt("Please enter your weight in kilograms"));

  console.log('Weight is ' + weight);

  if (isNaN(weight)) {
    console.log('This is not a number');
    alert('That is not a valid weight, please enter your weight in kilograms');
    weightInput();
  } else {
    console.log('This is a valid number. Your weight is ' + weight + ' kilograms.');
    calculateBMR();
    tableOutput();
  }

  function calculateBMR() {
    userBMR = weight * bmrMultiplier;
    console.log('Gender is ' + gender);
    console.log('Your weight is ' + weight + ' kilograms.');
    console.log("userBMR is " + userBMR);
  }

}


function tableOutput() {

  var body = document.body,
  tbl  = document.createElement('table');
  tbl.style.width  = '100px';
  tbl.style.border = '1px solid black';

  for (kph = 0; kph < 13; kph++) { 

    var tr = tbl.insertRow();

    for (hr = .25; hr < 2.75; hr = (hr + .25)) { 
      caloriesBurned = weight * kph * hr;
      console.log('kph is ' + kph + ' hours is ' + hr + ' calories burned is ' + caloriesBurned);

      var td = tr.insertCell();
      td.appendChild(document.createTextNode('Cell'));
      td.style.border = '1px solid black';


    }

  }

  body.appendChild(tbl);

}



genderInput();

1 个答案:

答案 0 :(得分:2)

你错误的原因是&#34; body&#34;变量为NULL。由于它是NULL,因此它没有方法appendChild。

<强>为什么吗

因为当你运行脚本时(我假设它是外部脚本并且你提供了整个脚本),所以还没有BODY标签!!!

在您提供的代码的末尾,您立即调用了函数genderInput(使用()符号)。通过这样做,您的脚本将不会等待整个HTML页面完成加载和运行。并且,正如您可以猜到的,它将在HTML到达body标签之前运行(因为您可能将脚本标记放在HTML标头中)

如何解决?

最简单最简单的方法是:

window.onload = genderInput //there are no () symbol

此代码将在运行genderInput函数

之前等待窗口(网页)完成加载