简体   繁体   中英

Accessing functions from within a Javascript Object (Javascript)

I am attempting to create a basic Hangman program. It's an array of tags which are assigned into an array of Objects (called Buttons). Each image is an image of a letter, so for example you would press the 'L' button, it would check whether this was in an WordArray (which is an array of chars), then it would act accordingly (to hide the letter, then update the gallows image if it needed to).

I cannot get the onclick method of the images to access the checkinarray function. What am i doing wrong?

var LetterAmount = 3; //make this 26. checked.
var WordArray = new Array();
var Buttons = new Array();

function checkinarray(num){
var z = 0;
while (z<4){
  document.write("looping through word now");
    if (num == WordArray[z]){
    document.write("<br/>it is in the word");
    }
  z++;
  }
}

function ButtonClicked(){
this.Image.src = "images/blank.jpg";
checkinarray(this.Number);
}
function Button(Image, Number) {
this.Image = Image;
this.Number = Number;
this.ButtonClicked = ButtonClicked;
}
function initialiseletters(){
var x;
//set up empty img tags for use
  for(i = 0; i < LetterAmount; i++) {
  document.write("<img id=" + i + ">");
  }
  for(x = 0; x < LetterAmount; x++) {
  document.images[x].src = "images/" + x + ".jpg";
  document.getElementById(x).onclick =function(){
  Buttons[this.id].ButtonClicked();
  } 
Buttons[x] = new Button(document.images[x], "" + x); 
}
}

function initialiseword(){
 //WordArray = new Array();
 WordArray[0] = 0;
 WordArray[1] = 1;
 WordArray[2] = 2;
 WordArray[3] = 3;
}

function initialise(){
initialiseword();
initialiseletters();
document.write("testing overall");
}

I'm not seeing a problem with ButtonClicked calling checkinarray , but I'm seeing a problem with checkinarray -- it's calling document.write after the page rendering is complete (eg, when the user clicks), which won't work. You need to modify the DOM via DOM methods (this will be made much easier if you use a toolkit like Prototype, jQuery, MooTools, Dojo, the Closure Library, YUI, etc.).

    document.getElementById(x).onclick =function(){
    Buttons[this.id].ButtonClicked();
    } 

Is where your problem is. 'this.id' is undefined.

document.write is not a good way to add elements to the DOM... Try document.createElement('img');

Then you already have reference to the image like so:

var img = document.createElement('img');
img.onclick = function()
{
    //your click...
}
//add it to the view stack
document.body.appendChild(img);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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