2013-08-22 241 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值。