【问题标题】:Vanilla JS Fizzbuzz does not work香草 JS Fizzbuzz 不起作用
【发布时间】:2015-10-19 20:10:18
【问题描述】:

我正在尝试添加一个从 1 到 100 的新 LI 循环,然后显示计数变量或 fizz/buzz/fizzbuzz。 让它在 Jquery 中工作,但不能在纯 JS 中工作。

代码:

<h1>Fbuzz</h1>
<div class="looping">
<ul id="list"></ul>
</div>


function myBuzz(){
  var ul =document.getElementById("list");
var newLi = document.createElement("li");

for ( var count = 1; count <= 100; count++) {
        if (count % 3 === 0 && count % 5 === 0) {
            newLi.appendChild(document.createTextNode("fiyyBuzz"));
        ul.appendChild(li);}
        else if (count % 3 === 0) {
            newLi.appendChild(document.createTextNode("fizz"));
        ul.appendChild(li);
        }
        else if (count % 5 === 0) {
        newLi.appendChild(document.createTextNode("Buzz"));
        ul.appendChild(li);}
        else {
            newLi.appendChild(document.createTextNode(count));
        ul.appendChild(li);
        }
    }
  }
myBuzz();

http://codepen.io/damianocel/pen/LpeEmM

【问题讨论】:

  • li 中的 ul.appendChild(li) 是什么?
  • 你如何让它在 jquery 中而不是在 vanilla 中工作?
  • 如果您查看控制台,您会发现那里有一个明显的错误。 Uncaught ReferenceError: li is not defined

标签: javascript loops fizzbuzz


【解决方案1】:

你必须为每个 for 循环创建一个新的 li 元素,然后将其保存到一个变量中......所以

var newLi, li;

for ( var count = 1; count <= 100; count++) {
     newLi = document.createElement("li");
     newLi.className = "newClassName";

     if (count % 3 === 0 && count % 5 === 0) {
        li = newLi.appendChild(document.createTextNode("fizzBuzz"));
     } else if (count % 3 === 0) {
        li = newLi.appendChild(document.createTextNode("fizz"));
     } else if (count % 5 === 0) {
        li = newLi.appendChild(document.createTextNode("Buzz"));
     } else {
        li = newLi.appendChild(document.createTextNode(count));
     }

     ul.appendChild(li);
}

在css中

.newClassName { 
   display: block;
}

【讨论】:

  • @Daemedeor,谢谢,这几乎成功了,不过我仍然需要定义 newLi 和 li。是的,我一开始根本没有声明“li”,我把它归咎于 jquery :-) 没有使用控制台,只依赖于 codepen 错误消息。现在,如何将生成的 li 显示为块元素,或者向其中添加 css 规则?
  • @damianocelent 你想看到更新,只需在 li 元素中添加一个新的类名,然后在 css 中正常设置样式
猜你喜欢
  • 2021-11-29
  • 2021-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多