我有一个使用ng2-smart-table的网络应用。我正在尝试检索所有单元格并将隐藏属性应用于它们。我以为放
cells = document.getElementsbyTagName("td")
在ngAfterViewInit()中可以做到这一点,但我不认为该表已经完成加载,因为我得到一个大小为0的htmlCollection。所以我想我会尝试使用回调函数。所以我在ngAfterViewInit()中使用了这段代码(第一次使用回调函数,所以我不确定这是否正确)。
let getCells = function(){
return document.getElementsByTagName("td");
}
let changeCells = function(callback){
let data = callback();
console.log(data.length);
if(data.length !== 1189){ changeCells(callback) }
else{ console.log(data.length); }
}
changeCells(getCells);
1189是有多少个细胞。我知道这是因为我在ngAfterViewInit()中放了以下代码,它给了我这个值(我期望的值)。
document.getElementById("columnButtonModal").setAttribute("href", "#columnInfoModal");
setTimeout(function(){
console.log(document.getElementsByTagName("td").length);
}, 150);
所以在我的回调函数中它只执行indefinitley,直到我的堆栈空间不足。我知道我可以使用setTimeout函数,但我觉得这不是解决这个问题的合适方法。任何帮助将不胜感激。这是我的ngOnInit()和ngAfterViewInit()代码。
ngOnInit() {
this.routingSubscription = this.route.params.subscribe(params => {
this.var = params["val"] || 'all';
this.source = new ServerDataSource(this.http, { endPoint: `webaddress` });
});
}
ngAfterViewInit(){
let getCells = function(){
return document.getElementsByTagName("td");
}
let changeCells = function(callback){
let data = callback();
console.log(data.length);
if(data.length !== 1189){ changeCells(callback) }
else{ console.log(data.length); }
}
changeCells(getCells);
/*
document.getElementById("columnButtonModal").setAttribute("href", "#columnInfoModal");
setTimeout(function(){
console.log(document.getElementsByTagName("td").length);
}, 150);
*/
}
答案 0 :(得分:1)
问题的直接根是递归调用。
let changeCells = function (callback) {
...
if (data.length !== 1189) { // <- The `data.length` does not become equal to 1189
changeCells(callback); // ...but the function is being recursively invoked,
// while `data` has not changed...
}
}
你需要完全没有这个嵌套的递归调用;或确保数据已调整为最终包含1189
个元素,否则您的代码将不再用完堆栈......