简体   繁体   English

HTML,Javascript:按钮未调用功能

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

I make a button in HTML, and I want it to call function in javascript: 我在HTML中创建了一个按钮,并且希望它在javascript中调用函数:

index.html 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 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();
}

The code runs fine if I put moveDot(); 如果我放置moveDot();则代码可以正常运行moveDot(); function inside setGameAreaBounds(); setGameAreaBounds();内部的函数setGameAreaBounds();

However, it seems like the button(id: startButton) never connects to function start(); 但是,似乎button(id:startButton)从未连接到函数start(); ;。

What did I do wrong? 我做错了什么?

Try moving your functions inside your onLoad function and link them back up to the global scope: 尝试将函数移到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();
}

Basically, your html functions are accessing functions defined in the global scope after the dom elements were created. 基本上,创建dom元素后,您的html函数将访问在全局范围内定义的函数。 So no reference to the function exists when the dom is created. 因此创建dom时不存在对该功能的引用。 The setGameAreaBounds function gets called after the dom is ready - onLoad. dom准备就绪 ,将调用setGameAreaBounds函数-onLoad。 JavaScript functions each have their own scope so you need to pass this from the parent using an unique reference. 每个JavaScript函数都有自己的作用域,因此您需要使用唯一的引用将其传递给父函数。 Then you can assign the names you want to the functions. 然后,您可以为功能分配所需的名称。

A better approach would be to define all scripts after Many programs use an onReady function that waits until the dom is loaded before defining any javascript functions. 更好的方法是在许多程序使用onReady函数之后定义所有脚本,该函数会等到dom被加载后再定义任何javascript函数。 This is a good approach. 这是一个好方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM