首页 > 解决方案 > 如何使用javascript在段落中显示代码

问题描述

我是一个 javascript 初学者。尝试在控制台中编写 fizzbuzz 代码,效果很好。但我无法在段落标签中显示结果。该标签很快就会更改为其默认值。预期输出 - 显示从 1 到 userInput 值。

<form>
    <label for="inputType"> Enter a number to start</label>
    <input  id ="inputType" type = "number" value="1">
    <button onclick="myFunction()"> Enter</button>
</form>

<p id="demo"> Result</p>

<script>
    function myFunction() {
        let userInput = document.getElementById("inputType").value;
        let para = document.getElementById("demo");
        for(let i=1;i<=userInput;i++){
            if(i% 3 === 0 &&  i%5 ===0) {
                para.textContent= "Fizzbuzz";
            } else if (i% 5 === 0){
                para.textContent = "buzz";
            } else if(i %3 === 0){
                para.textContent = "fizz";
            } else{
                para.textContent = i;
            }
        }
        return userInput;
    }
    myFunction();
</script>

标签: javascript

解决方案


The page is reloading after you click Enter button , to prevent that

Option 1: You can pass the event from the HTML and use preventDefault to stop from reloading

<form>
<label for="inputType"> Enter a number to start</label>
<input  id ="inputType" type = "number" value="1">
<button onclick="myFunction(event)"> Enter</button>
</form>
<p id="demo"> Result</p>
<script>
function myFunction(event) {
    event.preventDefault();
    let userInput = document.getElementById("inputType").value;
    let para = document.getElementById("demo");
for(let i=1;i<=userInput;i++){
 if(i% 3 === 0 &&  i%5 ===0) {
     para.textContent= "Fizzbuzz";
} else if (i% 5 === 0){
     para.textContent = "buzz";
} else if(i %3 === 0){
    para.textContent = "fizz";
} else{
    para.textContent = i;
}
 }
 return userInput;
}
</script>

Option 2: Add onSubmit handler in form tag and return false ,so that on submit it will not reload

<form onSubmit="return false">

Option 3: You can return false from the method and change the button tag as

<button onclick="return myFunction()"> Enter</button>

推荐阅读