啤酒瓶 - 这是什么:var bottlesDiv = document

Bottles of Beer - what is this: var bottlesDiv = document

我学习了一个非常基本的 Bottles of Beer 教程(与本网站上已经提到的教程不同),但我不明白这部分是做什么的:

var bottlesDiv = document.

完整代码在这里(它确实按预期工作):

 

var bottles = 99;
var lyrics = "";
while (bottles > 0) {
lyrics = lyrics + bottles + " bottles of beer on the wall <br>";
lyrics = lyrics + bottles + " bottles of beer <br>";
lyrics = lyrics + "Take one down, pass it around, <br>";
bottles = bottles - 1;
if (bottles > 0) {
 lyrics = lyrics + bottles + " bottles of beer on the wall <br><br>";
} else {
 lyrics = lyrics + "No more bottles of beer on the wall. <br>";
}
}
var bottlesDiv = document.
getElementById("bottles");
bottlesDiv.innerHTML = lyrics;
<!doctype html>
<html lang="en">
<head>
 <title>99 Bottles of Beer</title>
 <meta charset="utf-8">
 <link rel="stylesheet" href="style.css">
</head>
<body>
 <h1>99 Bottles of Beer </h1>
 <div id="bottles"></div>
</body>
</html>

其实就是多行JavaScript语句:

// define the bottlesDiv variable and assign to it
var bottlesDiv = document // start at window.document which is the root of the page
  .getElementById('bottles'); // find the element in document with id = bottles

写成这样肯定更有意义:

var bottlesDiv =
  document.getElementById('bottles');

var bottlesDiv = document.getElementById("bottles");

这只是格式不正确的情况。 bottlesDiv 是保存 id 为 bottles 的元素的变量。

getElementById() 是一个 Javascript 选择器函数。

不是

var bottlesDiv = 文档。

var bottlesDiv = document.getElementById("bottles");

一直读到分号。