javascript - "99 bottle of beer on the wall"代码不工作纯 js。 if 语句和 while 循环

标签 javascript if-statement while-loop

您好,我制作了一首 99 瓶啤酒歌曲,但我不确定我的代码似乎无法正常工作,我无法弄清楚。我真的需要一些帮助来了解我哪里出错了,或者需要一些人来告诉我我哪里出错了。我想要 if 语句或者如果有不同的方法可以做到这一点,但我需要设置它是如何我不确定如何修复它请帮忙。 提前致谢。

这是我的 JavaScript。

var bottles = 99
bottle = "bottles";
text = "";

var output = document.getElementById('output');
while (bottles > 0) {

    if (bottles == 1) {
    bottle = "bottle";
    text = "<p>" + bottles + " " + bottle + " of beer on the wall, " + bottles + " " + bottle + " of beer. <br/>";
    bottles--;

        output.innerHTML += text;
    }

    if (bottles == 0) {
    bottles = "no more";
    text += "Take one down and pass it around, " + bottles + " bottles of beer on the wall. </p>"

    output.innerHTML += text;
}

output.innerHTML += "<p> No more bottles of beer on the wall, no more bottles of beer. <br/> Go to the store and buy some more, 99 bottles of beer on the wall.</p>"

这是我的 HTML。

<title>My Title</title>
<script src="javascript.js"></script>
<div style="text-align: center;">
 <h1>99 Bottles of Beer Song</h1>

<div id="output"></div>

我也有一把 fiddle 。 http://jsfiddle.net/Matt1990/1wg16qr5/46/

最佳答案

您的代码充满错误。

要调试 JavaScript 等客户端代码,您可以使用 Chrome/Firefox 中的开发人员工具,方法是按 CTRL + SHIFT + i。它显示语法错误,如变量声明部分中的错误。

要进一步阅读,请参阅 Chrome DevTools Overview . Chrome 开发工具远比 Firefox/IE/其他(恕我直言)好

Chrome Developer tools


这是工作代码。请自行比较。

var bottles = 99,
    bottle = "bottles",
    text = "",
    output = document.getElementById('output');
while (bottles > 0) {
    if (bottles == 1) {
        bottle = "bottle";
    }

    text += bottles + " ";
    text += bottle + " of beer on the wall, ";
    text += bottles + " " + bottle + " of beer.<br>";
    
    bottles--;
    text += "Take one down and pass it around, ";
    text += + bottles + " bottles of beer on the wall.<hr>"

    if (bottles == 0) {
        bottles = "no more";
    }
    output.innerHTML += text;
  text = '';
}

output.innerHTML += " No more bottles of beer on the wall, no more bottles of beer.  Go to the store and buy some more, 99 bottles of beer on the wall.";
<div style="text-align: center;">
     <h1>99 Bottles of Beer Song</h1>

    <div id="output"></div>


关于javascript - "99 bottle of beer on the wall"代码不工作纯 js。 if 语句和 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25698940/

相关文章:

javascript - 使用 For 循环简化 IF...Else 语句 [Javascript]

java - 获取出现次数最大次数

c++ - 虽然循环在输入方面表现得很奇怪

javascript - jQuery Accordion

Javascript 重新加载 iframe

c# - 使用三元运算符了解 C# 编译错误

python - time.sleep在无限while循环内仅一部分代码

javascript - "var lthis = this, someObj"在 javascript 中的含义

javascript - 如何监听指令中文本区域的变化?

javascript - jQuery//为什么这个 if 语句不正确?