gpt4 book ai didi

javascript - 在 JS 中通过 div 运行的 forEach() 给出错误

转载 作者:行者123 更新时间:2023-11-30 11:42:37 24 4
gpt4 key购买 nike

我在一个数组中有几个 div,我想更改它们的高度,即使当我记录 div 的名称并为我提供正确的对象名称时,我仍然收到“这是未定义的”错误控制台中的消息。

就像我说的,当我注销所有 div 的名称时,它们已正确给出,但在我想设置它们高度的那一行,我猜某处“this”有问题。

this.divs.forEach(names);
function names(div) {
console.log(div); //goes thought all the divs correctly
this._renderer.setElementStyle(div.nativeElement, 'height', largestHeight + 'px');
}

我在 angular2 中做这件事,以防有人想知道。问候任何帮助。

最佳答案

你的函数上下文中没有this,尝试使用箭头函数:

this.divs.forEach((names) => {
...
});

您还可以将 this 绑定(bind)到您的函数。

this.divs.forEach(names.bind(this));

关于javascript - 在 JS 中通过 div 运行的 forEach() 给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42071219/

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