Reputation: 101
Sorry for not giving a clear title, because I don't know why my script doesn't work.
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 ?
};
Btw, is there a better way to achieve my goal: creat some objects; with each object, creat a button; when a button is clicked, do some function.
Upvotes: -1
Views: 96
Reputation: 428
Please check this code
$(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);
}
});
there some minor mistake. document.body always pass null. For that script run between document.ready function for get document.body value.
Upvotes: 0
Reputation: 7642
try pushing the person objects to all array
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);
Upvotes: 0
Reputation: 9612
Try this out:- 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 ?
};
Upvotes: 1
Reputation: 796
In the line
this.func=function(){alert(this.name)};
replace
this.nameto just
name, since you're calling it out of scope, your this is different (it's the button - object HTMLInputElement).
Upvotes: 0
Reputation: 8715
When you are clicking on the button, the context of the event handler (this
variable) becomes the button itself. You can check it simply putting console.log(this)
inside a func
.
I would recommend the following code:
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]);
};
Using bind()
you explicitly push the desired context into the function.
More on bind.
Upvotes: 2