函数在未被调用时执行

时间:2017-03-11 18:35:36

标签: javascript html css

出于某种原因,这两个函数已经执行,但它们只应在单击按钮后才能运行。按钮分配给不同的功能。

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

<!-- 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>
{{1}}

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

@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(2)">Click Me</button>
<p id="ml">This should change from 2 pints into ml</p>
<button onclick="PINTStoLITRES(5)">Click Me</button>
<p id="litres">This should change from 5 pints to litres</p>
<p style="color:red; font-weight:bold">WORKING Version6!!!!!!!!</p>
<p>For some reason, the function already executes before clicking the buttons...</p>
<script>
function PINTStoML(pints) {
	var p = pints * 568.2612;
  document.getElementById("ml").innerHTML = p;
}

function PINTStoLITRES(pints) {
  var p = pints * 0.568261;
  document.getElementById("litres").innerHTML = p;
}

</script>
</section>