为什么我的webbrowser不保存我的javascript输出?
我正在尝试开发一段简单的代码。。我创建了一个计算器,根据HTML输入计算Celcius/Kelvin/Fahrenheit。代码似乎正在运行。正确的答案出现了,但在一瞬间消失了,浏览器似乎在“刷新”。我错过什么了吗 Html代码:为什么我的webbrowser不保存我的javascript输出?,javascript,html,Javascript,Html,我正在尝试开发一段简单的代码。。我创建了一个计算器,根据HTML输入计算Celcius/Kelvin/Fahrenheit。代码似乎正在运行。正确的答案出现了,但在一瞬间消失了,浏览器似乎在“刷新”。我错过什么了吗 Html代码: <html> <body> <form> <label for="degrees">Degrees: </label> <input type="text&
<html>
<body>
<form>
<label for="degrees">Degrees: </label>
<input type="text" name="degrees" id="degrees">
<label for="calc_type">Type: </label>
<select name="calc_type" id="calc_type">
<option value="celcius">Celcius</option>
<option value="kelvin">Kelvin</option>
<option value="fahrenheit">Fahrenheit</option>
</select>
<input type="submit" value="Submit" onclick="myFunction()">
</form>
<table style="width: 100px">
<tr>
<th>Celcius: </th>
<th id="celsius_value">0</th>
<tr></tr>
<th>Fahrenheit: </th>
<th id="fahrenheit_value">0</th>
<tr></tr>
<th>Kelvin: </th>
<th id="kelvin_value">0</th>
</tr>
</table>
</body>
<script src="js/celcius_calulator.js"></script>
</html>
“提交”按钮将通过
将表单内容发布到指定为表单目标的任何位置。由于您没有指定任何内容,它只会将表单内容发布到当前页面
你必须做一些类似的事情
document.querySelector('form').addEventListener('submit',e=>e.preventDefault())
防止表单被提交,这将再次防止页面重新加载
然后,您还可以在事件侦听器中执行求值逻辑,这样就不会有两个事件侦听器(一个用于提交按钮,一个用于表单提交事件)。最简单的答案是将
事件作为myFunction(event)
中的参数传递,然后执行event.preventDefault()。只需将事件作为以下参数传递->
<input type="submit" value="Submit" onclick="myFunction(event)">
您可以在代码中进行以下更改
<input type="button" value="Submit" onclick="myFunction()">
希望这能解决您的问题。您的输入在
中,表单正在提交。缺少“action”属性,默认行为是重新加载页面。
function myFunction(event) {
event.preventDefault();
var degrees = document.getElementById('degrees').value
var calc_type = document.getElementById('calc_type').value
if (calc_type === "celcius") {
cC(degrees);
} elseif (calc_type === "fahrenheit"); {
fC(degrees);
} elseif (calc_type === "kelvin"); {
kC(degrees)
}
<input type="button" value="Submit" onclick="myFunction()">