search

Home  >  Q&A  >  body text

Questions about javascript recursive functions. Please ask a master.

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!

漂亮男人漂亮男人2712 days ago691

reply all(2)I'll reply

  • 我想大声告诉你

    我想大声告诉你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.

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

    reply
    0
  • 世界只因有你

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

    reply
    0
  • Cancelreply