[英]onclick Event Firing Even without Click
即使沒有點擊,我的onclick事件也會觸發。 我不確定為什么嗎? 下面是我的代碼。 應該首先加載主頁面板,並且當用戶單擊aboutButton時,應該將它們帶到About面板。
JS Bin: http : //jsbin.com/alebox/1/edit
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script>
function myOnloadFunc() {
var homePanel = document.getElementById("homePanel");
var aboutPanel = document.getElementById("aboutPanel");
var settingsPanel = document.getElementById("settingsPanel");
var gamePanel = document.getElementById("gamePanel");
var resultsPanel = document.getElementById("resultsPanel");
// All panels in app
var panels = [homePanel, aboutPanel, settingsPanel, gamePanel, resultsPanel];
// Show selected panel and hide all other panels
function showPanel(panel) {
for (var i = 0; i < panels.length; i++) {
if (panels[i] === panel) {
// Show panel
// this referred to global object, i.e. window
panels[i].style.display = "block";
} else {
// Hide
panels[i].style.display = "none";
}
}
}
showPanel(homePanel);
// CODE THAT IS GIVING ME A PROBLEM /////////////////////////
var aboutButton = document.getElementById("aboutButton");
aboutButton.onclick = showPanel(aboutPanel);
// CODE THAT IS GIVING ME A PROBLEM /////////////////////////
}
window.onload = myOnloadFunc;
</script>
</head>
<body>
<!-- homePanel -->
<div class="panel" id="homePanel">
<div align="center">
<p><strong>Web App</strong></p>
<p><a id="playButton">Play</a> <a id="aboutButton">About</a></p>
</div>
</div>
<!-- aboutPanel -->
<div class="panel" id="aboutPanel">
About panel
</div>
<!-- settingsPanel -->
<div class="panel" id="settingsPanel">
Settings panel
</div>
<!-- gamePanel -->
<div class="panel" id="gamePanel">
Game panel
</div>
<!-- resultsPanel -->
<div class="panel" id="resultsPanel">
Results panel
</div>
</body>
</html>
之所以射擊,是因為您馬上就調用它!
所以你要:
aboutButton.onclick = function(){showPanel(aboutPanel);};
要將功能附加到事件,僅應提供對該功能的引用。 實際上,您在使用()時正在調用該函數。
綁定事件的代碼應為:
aboutButton.onclick = showPanel;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.