gpt4 book ai didi

javascript - 为什么我的函数运行不正常?

转载 作者:行者123 更新时间:2023-11-28 15:56:57 25 4
gpt4 key购买 nike

抱歉没有给出明确的标题,因为我不知道为什么我的脚本不起作用。

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

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

最佳答案

当您单击按钮时,事件处理程序的上下文(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.

关于javascript - 为什么我的函数运行不正常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18373218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com