2016-04-03 67 views
0

我做HTML中的按鈕,我想它來調用函數在javascript:HTML,Java腳本:按鈕不調用函數

的index.html

<body onLoad="setGameAreaBounds()" onResize="setGameAreaBounds()"> 
     <div id="scoreLabel">Score: 0 </div> 

     <!--div Group--> 
     <div> 
      <p id="pageTitle">Button Chaser</p> 
      <input type="button" id="startButton" onClick="start()" value="Start"/> 
     </div> 

     <!--The following: gameArea and dot is grouped together--> 
     <div id="gameArea"> 
      <button id="dot" onClick="detectHit()"></button> 
     </div> 

</body> 

buttonChaser.js

function detectHit() { 
    //Increase the var score 
} 

function setGameAreaBounds() { 
    //Setting the size of GameBoard/Window 
} 



function moveDot() { 
    //randomly move the button(id: dot) within the GameBoard/window 
} 

function start() { 
    alert("sometext"); 
     moveDot(); 
} 

的代碼運行正常,如果我把moveDot();函數內部setGameAreaBounds();

然而,這似乎是按鈕(ID:startButton)從未連接的功能start();

我做了什麼錯?

+0

請張貼控制檯錯誤。 –

+0

我使用的是Firefox>開發人員> Web控制檯。當我點擊開始,它說:'TypeError:開始不是一個函數'然後在它下面:'onClick()index.html:1'它是否足夠的信息? – user2789240

回答

1

嘗試移動你的onLoad函數內部的功能和連接它們備份到全球範圍:

var score = 0; 
var aWidth; 
var aHeight; 
var timer; 

var that = this; 

function setGameAreaBounds() { 
    //Setting the size of GameBoard/Window 

    that.moveDot = function() { 
     //randomly move the button(id: dot) within the GameBoard/window 
    } 

    that.detectHit = function() { 
     //Increase the var score 
    } 

    that.start = _start; // link desired name to reference to existing function 

} 

function() _start { 
    alert("sometext"); 
    moveDot(); 
} 

基本上,你的HTML功能訪問在全球範圍內定義的函數創建的DOM元素之後。因此,在創建dom時不存在對函數的引用。 setGameAreaBounds函數在 dom準備好之後調用- onLoad。 JavaScript函數都有自己的作用域,所以你需要使用唯一的引用從父類傳遞它。然後你可以分配你想要的功能名稱。

更好的方法是在定義所有腳本之後定義所有腳本 許多程序使用onReady函數,在定義任何javascript函數之前等待dom被加載。這是一個好方法。

+0

問題海報將從學習他們做錯了什麼以及如何解決他們的問題中受益。 –

+2

謝謝@MatthewCliatt,但許多人,包括我自己,發帖和回答,並花了幾分鐘時間改進它。 – chriskelly

+0

好點。建議編輯前我會再等一會兒。 –