简体   繁体   English

我的JavaScript无法正确生成HTML

[英]My JavaScript isn't generating HTML correctly

This is the HTML: 这是HTML:

<body>
    <p>Below the input bubbles the numbers from 1 - 100 will be printed. Any number that is the multiple of the Fizz, will have Fizz instead of the number and the same goes for Buzz. Any number that is a multiple of both of the numbers is printed as FizzBuzz.</p>
    <input type="text" id="fizz" name="fizz" placeholder="Enter the fizz number">
    <input type="text" id="buzz" name="buzz" placeholder="Enter the buzz number">
    <p id="fizzbuzz"></p>
</body>

This is the JavaScript. 这是JavaScript。 I think this is the problem but I am not 100% sure: 我认为这是问题所在,但我不确定100%:

$(document).ready(function() {
    var fizz = document.getElementById('fizz').value;
    var buzz = document.getElementById('buzz').value;
    var p = document.getElementById('fizzbuzz');

    for (var i = 1; i < 101; i++) {
        if (i % fizz === 0 && i % buzz === 0) {
            p.innerHTML = p.innerHTML + i + "FizzBuzz, ";
        } else if (i % fizz === 0) {
            p.innerHTML = p.innerHTML + i + "Fizz, ";
        } else if (i % buzz === 0) {
            p.innerHTML = p.innerHTML + i + "Buzz, ";
        } else {
            p.innerHTML = p.innerHTML + i + ", ";
        }
    }
});

Your code seems to be using jQuery, but is not included jQuery. 您的代码似乎正在使用jQuery,但没有包含jQuery。

If you don't have jQuery included, then instead of $(document).ready() use DOMContentLoaded . 如果您没有包含jQuery,请使用DOMContentLoaded代替$(document).ready()

You also will need a change event handler to update the result when the input values are changed 当输入值更改时,您还需要一个change事件处理程序来更新结果

 document.addEventListener("DOMContentLoaded", function(event) { var elfizz = document.getElementById('fizz'); var elbuzz = document.getElementById('buzz'); var p = document.getElementById('fizzbuzz'); function changehandler() { var fizz = +elfizz.value || 1; var buzz = +elbuzz.value || 1; var html = ''; for (var i = 1; i < 101; i++) { if (i % fizz === 0 && i % buzz === 0) { html += i + "FizzBuzz, "; } else if (i % fizz === 0) { html += i + "Fizz, "; } else if (i % buzz === 0) { html += i + "Buzz, "; } else { html += i + ", "; } } p.innerHTML = html; } elfizz.addEventListener('change', changehandler); elbuzz.addEventListener('change', changehandler); changehandler(); }); 
 <p>Below the input bubbles the numbers from 1 - 100 will be printed. Any number that is the multiple of the Fizz, will have Fizz instead of the number and the same goes for Buzz. Any number that is a multiple of both of the numbers is printed as FizzBuzz.</p> <input type="text" id="fizz" name="fizz" placeholder="Enter the fizz number"> <input type="text" id="buzz" name="buzz" placeholder="Enter the buzz number"> <p id="fizzbuzz"></p> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM