2013-08-22 246 views
0

對不起沒有明確的標題,因爲我不知道爲什麼我的腳本不起作用。爲什麼我的功能不正確?

var all=[]; 
function People(name){ 
    this.name=name; 
    this.func=function(){alert(this.name)}; 
    all.push(this); 
}; 
var person1=new People('Peter'); 
for(i=0;i<all.length;i++){ 
    var newBtn=document.createElement('input'); 
    document.body.appendChild(newBtn); 
    newBtn.type='button'; 
    newBtn.value=all[i].name; 

    newBtn.onclick=all[i].func; // why doesn't is say "Peter" when I click the button ? 
}; 

順便說一下,有沒有更好的方法來實現我的目標:創建一些對象;與每個對象一起,創建一個按鈕;當一個按鈕被點擊時,做一些功能。

+1

@KirenSiva通常是一個很好的問題,但不需要大聲呼喊。 :) –

+0

@KirenSiva他沒有說這是在拋出一個錯誤,他說當他點擊按鈕時並沒有提醒'彼得'。 – Barmar

回答

3

當您單擊按鈕時,事件處理(this變量)的情況下成爲按鈕本身。您可以檢查它,只需將console.log(this)放入func
我建議以下代碼:

for(i=0;i<all.length;i++){ 
    var newBtn=document.createElement('input'); 
    document.body.appendChild(newBtn); 
    newBtn.type='button'; 
    newBtn.value=all[i].name; 

    newBtn.onclick=all[i].func.bind(all[i]); 
}; 

使用bind()你明確地推所需的環境下進入功能。
More on bind.

+0

+1是的,我剛剛做到了,添加了console.log(這個),來回答...並且你打我XD –

+0

@Artyom Neustroev謝謝你,你的建議工作正常。我會嘗試用(姓名)替換(this.name),如其他人所建議的。如果我得到任何錯誤,我會仔細看看bind() – Erik

0

試推人反對所有陣列

var all=[]; 
function People(name){ 
    this.name=name; 
    this.func=function(){alert(this.name)}; 
}; 


var person1=new People('Peter'); 

//push the person objects 

all.push(person1); 
0

在行

this.func=function(){alert(this.name)}; 

更換

this.name
只是
name
,因爲你調用它的範圍,你這是不同的(它的按鈕 - 對象HTMLInputElement)。

1

嘗試了這一點: - http://jsfiddle.net/adiioo7/NCTMD/1/

JS: -

var all=[]; 
function People(name){ 
    this.name=name; 
    this.func=function(){alert(name)}; 
    all.push(this); 
}; 
var person1=new People('Peter'); 
for(i=0;i<all.length;i++){ 
    var newBtn=document.createElement('input'); 
    document.body.appendChild(newBtn); 
    newBtn.type='button'; 
    newBtn.value=all[i].name; 

    newBtn.onclick=all[i].func; // why doesn't is say "Peter" when I click the button ? 
}; 
0

請檢查該代碼

$(document).ready(function(){ 
    var all=[]; 
    function People(name){ 
     this.name=name; 
     this.func=function(){alert(name)}; 
     all.push(this); 
    }; 
    var person1=new People('Peter'); 

    for(i=0;i<all.length;i++){ 
     var newBtn=document.createElement('input'); 
     newBtn.type='button'; 
     newBtn.value=all[i].name; 
     newBtn.onclick=all[i].func; 
     document.body.appendChild(newBtn); 

    } 
}); 

有一些小的失誤。 document.body總是傳遞null。對於那個在document.ready函數之間運行的腳本來獲取document.body值。