javascript - 函数在未被调用时执行

标签 javascript html css

出于某种原因,这两个函数已经执行,但它们应该只在单击按钮后起作用。并且按钮被分配给单独的功能。

有人可以阐明为什么在按下按钮之前功能已经执行了吗?谢谢你的帮助

@charset "UTF-8";
/* CSS Document */

body{
	height:1000px;
	width:100%;
	background:#fff;
	margin:0;
}

.divider{
	width:100%;
	height:auto;
	background:#CCC;
	display:block;
	margin:10px;
}

h2{
	font-size:16px;
	display:block;
}
#confirm-paragraph{}
#global-variable-paragraph{}
#user-input{}
#expressions{}
#elephant-paragraph{}
#method-1{}
#method-2{}
#ml{}
#litres{}
#conditional-operator{}
#cast-1{}
#cast-2{}
<!-- Checklist: Arguments -->
<!-- Checklist: Return Values from Functions -->
<section class="divider">
<h2>Arguments Example</h2>
<button onclick="PINTStoML()">Click Me</button>
<p id="ml">This should change from 2 pints into ml</p>
<button onclick="PINTStoLITRES()">Click Me</button>
<p id="litres">This should change from 5 pints to litres</p>
<p style="color:red; font-weight:bold">NOT WORKING Version6!!!!!!!!</p>
<p>For some reason, the function already executes before clicking the buttons...</p>
<script>
function PINTStoML(pints) {
	return pints * 568.2612;
}
document.getElementById("ml").innerHTML = PINTStoML(2);

function PINTStoLITRES(pints) {
	return pints * 0.568261;
}
document.getElementById("litres").innerHTML = PINTStoLITRES(5);
</script>
</section>

最佳答案

它们正在执行,因为它们被 document.getElementById("litres").innerHTML = PINTStoLITRES(5); 调用; 发生这种情况是因为随着页面的加载,脚本也在加载,并且代码的任何未 protected 部分(例如那个部分)将执行并启动其他功能。

关于javascript - 函数在未被调用时执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42739072/

相关文章:

javascript - polymer 重复模板问题

css - 我如何在 Chrome 中的 css 转换顶部使用 DIV 的悬停效果? (在 FF 中有效)

Javascript - 在数组中查找最频繁的数字,即使有两个

javascript/jquery 为每个列表项切换一个元素

html - 尝试将 "information button"添加到我页面上的图片中,该图片仅在悬停时出现

jquery气球移动效果

css - Material Design 中提升元素的框阴影中的多个阴影

css - 为什么 Anchor 仍然使用默认的 css,即使我设置了不同的样式 (GWT)?

javascript - 立即运行函数,然后在指定时间后运行

javascript - 网页包 - 'velocity is not defined'