javascript - 如何使用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>
解决方案
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>
推荐阅读
- c# - 接收端ECDSA解密过程
- javascript - 在 ASP 页面中调用 Java Script 函数不返回任何内容
- javascript - 如何在多个元素上调用相同的 onclick 函数?
- javascript - 使用 useEffect 钩子停止反应导致无限循环
- python - 我的 conda 通道出现问题并导致 tensorflow 导入错误
- date - Crystal Reports - 如果日期字段大于今天,则为今天,否则日期字段
- amazon-web-services - 通过端点调用 SageMaker Notebook 实例函数
- c++ - cpp中向量的默认初始化程序是什么(或如何制作)?
- google-analytics - 在不复制标签的情况下发送更多 GTM 事件数据
- javascript - react-native 代码的哪一部分会重新渲染每个更改?