由于某种原因,这两个函数已经执行,但它们只应该在单击按钮后才能运行。这些按钮被分配给不同的函数。
有人能解释一下为什么函数在按按钮之前就已经执行了吗?谢谢你的帮忙
@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>
发布于 2017-03-11 18:47:53
@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>
发布于 2017-03-11 18:39:32
它们之所以执行是因为它们是由document.getElementById("litres").innerHTML = PINTStoLITRES(5);调用的,这是因为在加载页面时,脚本也是如此,代码中任何不受保护的部分(如该部分)都将执行和启动其他函数。
https://stackoverflow.com/questions/42739072
复制相似问题