簡體   English   中英

HTML,Javascript:按鈕未調用功能

[英]HTML, Javascript: button doesn't call function

我在HTML中創建了一個按鈕,並且希望它在javascript中調用函數:

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();則代碼可以正常運行moveDot(); setGameAreaBounds();內部的函數setGameAreaBounds();

但是,似乎button(id:startButton)從未連接到函數start(); ;。

我做錯了什么?

嘗試將函數移到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();
}

基本上,創建dom元素后,您的html函數將訪問在全局范圍內定義的函數。 因此創建dom時不存在對該功能的引用。 dom准備就緒 ,將調用setGameAreaBounds函數-onLoad。 每個JavaScript函數都有自己的作用域,因此您需要使用唯一的引用將其傳遞給父函數。 然后,您可以為功能分配所需的名稱。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM