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 ?
};

顺便说一句,有没有更好的方法来实现我的目标:创建一些对象;为每个对象创建一个按钮;单击按钮时,执行某些功能。

4

5 回答 5

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()您将所需的上下文显式推送到函数中。
更多关于绑定。

于 2013-08-22T06:36:55.480 回答
1

试试这个:- http://jsfiddle.net/aidioo7/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 ?
};
于 2013-08-22T06:38:18.977 回答
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);
于 2013-08-22T06:36:48.560 回答
0

在行

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

代替

这个名字
只是
姓名
,因为你在范围之外调用它,所以你的 this 是不同的(它是按钮 - 对象 HTMLInputElement)。

于 2013-08-22T06:37:25.907 回答
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 值。

于 2013-08-22T07:06:02.607 回答