这是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>
这是JavaScript。我认为这是问题,但我不是百分百肯定:
$(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 + ", ";
}
}
});
答案 0 :(得分:1)
您的代码似乎使用的是jQuery,但不包含在jQuery中。
如果您没有包含jQuery,则代替$(document).ready()
使用DOMContentLoaded。
您还需要一个更改事件处理程序,以便在更改输入值时更新结果
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>