簡體   English   中英

從Javascript對象(Javascript)中訪問函數

[英]Accessing functions from within a Javascript Object (Javascript)

我正在嘗試創建一個基本的Hangman程序。 它是一個標簽數組,分配給一個對象數組(稱為按鈕)。 每個圖像都是一個字母的圖像,因此,例如,您將按下“ L”按鈕,它將檢查它是否在WordArray(是一個字符數組)中,然后它會相應地執行操作(以隱藏字母,然后根據需要更新絞架圖像)。

我無法獲取圖像的onclick方法來訪問checkinarray函數。 我究竟做錯了什么?

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");
}

我沒有看到ButtonClicked調用checkinarray的問題,但是我看到了checkinarray的問題-頁面渲染完成后(例如,當用戶單擊時)它正在調用document.write ,這是行不通的。 您需要通過DOM方法修改DOM(如果您使用Prototype,jQuery,MooTools,Dojo,Closure Library,YUI等工具包,這將變得更加容易)。

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

是您的問題所在。 'this.id'未定義。

document.write不是向DOM中添加元素的好方法。嘗試document.createElement('img');

然后,您已經像這樣引用了圖像:

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

暫無
暫無

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

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