Questions about javascript recursive functions. Please ask a master.
漂亮男人
漂亮男人 2017-06-28 09:24:22
0
2
615

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!

漂亮男人
漂亮男人

reply all(2)
我想大声告诉你

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.

Update

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)
    }
};
世界只因有你

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)
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!