2011-08-27 44 views
0

当我运行此操作时,我的网页崩溃:我的代码中是否有无限循环?

function replace() 
{ 
    var str = document.getElementById('feeds'); 
    var cont = str.innerHTML; 
    curstring = "twitter: "; 
    while (cont.indexOf(curstring)) 
    { 
     replaced = cont.replace(curstring,"TWIMG "); 
     str.innerHTML = replaced; 
    } 
} 
+0

你试过用调试器试过吗? – fvu

+1

您可能想要检查您的TAB键是否正在工作......':p' –

回答

0

是的。你永远不会重新分配续。也许试试这个?

function replace() 
{ 
    var str = document.getElementById('feeds'); 
    var cont = str.innerHTML; 
    curstring = "twitter: "; 
    while (cont.indexOf(curstring) != -1) 
    { 
    replaced = cont.replace(curstring,"TWIMG "); 
    str.innerHTML = replaced; 
    cont = str.innerHTML; 
    } 
} 
+0

完美!谢谢! –

2

是的,当curstringcont。在您的while回路cont将不会更改,所以cont.indexOf(curstring)将永远是true

1

也许,是的。

cont.indexOf()测试应该测试>= 0,由于未找到该函数返回-1,其评估真正并会导致循环再绕过去。

它现在只会终止,如果cont开始curstring

根据其他答案,您还需要在循环内覆盖cont

function replace() { 
    var curstring = "twitter: "; 
    var str = document.getElementById('feeds'); 

    var cont = str.innerHTML; 
    var old = cont; 

    // NB: indexOf() returns -1 on failure, so you 
    //  must compare against that, 
    while (cont.indexOf(curstring) >= 0) { 
    cont = cont.replace(curstring, "TWIMG "); 
    } 

    // taken outside the loop so we don't modify the DOM 
    // over and over if the match is repeated - only update 
    // the DOM if the string got changed 
    if (cont !== old) { 
    str.innerHTML = cont; 
    } 
} 
+0

谢谢,它工作! –

+0

另外,不需要检查> = 0,因为如果它返回-1,它将评估为false。 –

+0

@aerobit不,你错了。 '!! - 1 === true' – Alnitak

0

cont从来没有在循环会改变,所以如果cont.indexOf(curstring)是真的,那将是真正的永远和你的程序进入一个无限循环。