Good evening, Master, please help me find out why my function cannot be executed?
Description of the situation: Since the table in p is loaded through ajax, the purpose of the function is to determine whether there is such a table. If so, make its background red. If not, execute the following function after 1 second. But now when the table has been loaded and displayed, the find() function does not make the table turn red (error report: Uncaught RangeError: Maximum call stack size exceeded)
Thank you in advance, masters!
我想大声告诉你2017-06-28 09:26:22
Because you use p.getElementsByTagName('table')[0]
What you get is a DOM object. Since the DOM object does not have the .length
attribute, target.length
is actually undefined. The value of undefined > 0
is always false
, so you will call the else
branch infinitely, so you will also add countless find(p)
bindings. Therefore, the browser prompts that the number of calls to find
exceeds the maximum limit.
The correct approach is to let target
be p.getElementsByTagName("table")
. This is an array and has the value of .length
.
Code:
Option 1: (Judge the array length of all tables and take the first operation)
function find(p) {
var target = p.getElementsByTagName("table");
if (target.length > 0) {
target[0].style.background = 'red';
} else {
setTimeout(function() {
find(p);
}, 1000)
}
};
Option 2: (Directly judge the table and directly operate the obtained table)
function find(p) {
var target = p.getElementsByTagName("table")[0];
if (target) {
target.style.background = 'red';
} else {
setTimeout(function() {
find(p);
}, 1000)
}
};
世界只因有你2017-06-28 09:26:22
target.length
target is table, what is table.length?
Please refer to it
function find(p) {
var interval = setInterval(function () {
var target = p.getElementsByTagName("table")[0]
if (target) {
clearInterval(interval)
target.style.background = 'red'
}
}, 1000)
}