使用 JavaScript 在网页上显示算法的输出



我尝试制作一个小的嘶嘶声算法

function fizzbuzz(num){
for (let i = 1; i <=  num; i++) {    
if(i%3===0 && i%5===0){
console.log("Fizzbuzz");
}    
else if (i%3===0) {
console.log("fizz");
}
else if(i%5===0){
console.log("buzz");
}
else{
console.log(i);
}
}

}

console.log(嘶嘶声(20((;

它使用控制台工作正常.log但现在我想构建一些东西,它从文本字段中获取输入,并在单击按钮后在网页本身上显示该算法的输出。我是 dom 的新手,我尝试了 document.write((,但它似乎不起作用。

谢谢。

"让你的函数变成HTML"实际上很容易:

  • 只需创建一个输入字段,以便用户可以键入一个数字
  • 创建一个按钮,在单击函数时触发函数
  • 确保将输入值作为参数传递给函数
  • 调整函数输出,使其显示在页面上

function fizzbuzz(num) {
for (let i = 1; i <= num; i++) {
if (i % 3 === 0 && i % 5 === 0) {
document.getElementById('output').innerHTML += "fizzbuzz<br>";
} else if (i % 3 === 0) {
document.getElementById('output').innerHTML += "fizz<br>";
} else if (i % 5 === 0) {
document.getElementById('output').innerHTML += "buzz<br>";
} else {
document.getElementById('output').innerHTML += i + "<br>";
}
}
}
<input type="number" id="input"><input type="button" onclick="fizzbuzz(document.getElementById('input').value)" value="Go!">
<p id="output"></p>

使用 HTML 和 Javascript 的嘶嘶声

jQuery(document).ready(function($) {



$("#go").click(function () { 
var i = $("#myNumber").val(); 
if (i == ''  || isNaN(i) ){ 
$("#myAnswer").text("enter a number"); //throw this error
return;
} 
var num = ''; //create a variable num
num += (i % 3 === 0) ? 'Fizz' : ''; //if num is divisable by 3 say fizz & continue else continue
num += (i % 5 === 0) ? 'Buzz' : ''; //if num is divisable by 5 say buzz & continue else continue
num = (num === '') ? i : num; //if num is not divisable by 3 or 5 return the user input
$("#myAnswer").text(num); //display results
});



});
.container {
background:#ccc;
border: 1px solid #333;
border-radius:5px;
box-shadow: 2px 2px 10px #333;
margin: 100px auto;
padding:50px;
text-align: center;
width: 250px;
}
#myAnswer {
color: #333;
font-weight: bold;
text-transform: uppercase;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<title>FizzBuzz</title>
</head>
<body>
<div class="container">
<input type="text" placeholder="Enter a Number" id="myNumber" maxlength="3" />
<input type="button" value="go!" id="go" />
<p id="myAnswer"> </p>
</div>
</body> 
</html>

最新更新