javascript遞歸函數(shù)問題求大神看看
問題描述
大神晚上好,請幫我看看我的函數(shù)為什么不能執(zhí)行呢?情況說明:由于p中的table是通過ajax加載過來的,函數(shù)的目的是判斷有沒有這table,如果有則讓其背景變紅,沒有的話,就1秒后再執(zhí)行以下這個函數(shù),但是現(xiàn)在當table已經加載顯示后,find()函數(shù)并沒有讓table變紅(報錯:Uncaught RangeError: Maximum call stack size exceeded)先謝謝大神們了!
問題解答
回答1:因為你用p.getElementsByTagName(’table’)[0]這個取到的是一個DOM對象,由于DOM對象沒有.length屬性,所以target.length其實是未定義的。而undefined > 0的值一直是false,所以你會無限次地調用else分支,所以也就會添加無數(shù)次的find(p)綁定。所以瀏覽器提示find調用次數(shù)超出最大限制。
正確的做法是讓target為p.getElementsByTagName('table'),這才是一個數(shù)組,才有.length的值。
Update代碼:方案1:(判斷取到所有table的數(shù)組長度,并取第一個操作)
function find(p) { var target = p.getElementsByTagName('table'); if (target.length > 0) {target[0].style.background = ’red’; } else {setTimeout(function() { find(p);}, 1000) }};
方案2:(直接判斷table,并直接操作取到的table)
function find(p) { var target = p.getElementsByTagName('table')[0]; if (target) {target.style.background = ’red’; } else {setTimeout(function() { find(p);}, 1000) }};回答2:
target.length target 是 table, table.length 是什么?
參考一下
function find(p) { var interval = setInterval(function () { var target = p.getElementsByTagName('table')[0] if (target) { clearInterval(interval) target.style.background = ’red’ } }, 1000)}
相關文章:
1. 數(shù)據(jù)庫 - MySQL 單表500W+數(shù)據(jù),查詢超時,如何優(yōu)化呢?2. javascript - 百度echarts series數(shù)據(jù)更新問題3. 求大神幫我看看是哪里寫錯了 感謝細心解答4. MySQL客戶端吃掉了SQL注解?5. mac 安裝 python_MySQLdb6. javascript - 圖片能在網站顯示,但控制臺仍舊報錯403 (Forbidden)7. php自學從哪里開始?8. mysql - AttributeError: ’module’ object has no attribute ’MatchType’9. python小白的基礎問題 關于while循環(huán)的嵌套10. phpstady在win10上運行
