2013-10-15 169 views
0

我有一個全局變量「isOnSecond」,它最初被設置爲falseJavaScript邏輯問題

這是連接到檢測布爾值if語句,如果這是真的有些動作被執行,然後布爾是設置回false。因此我希望這項行動能夠在一半時間內完成。

我的問題是這樣的,我知道我在這個函數中有邏輯問題,但是在這一點上我似乎無法想出一個解決方案。

我應該如何重新使用我想要的邏輯工作這個功能?

function transComplete() 
{ 
    slideTransStep = 0; 
    crtSlideIndex = nextSlideIndex; 
    alert(isOnSecond); 

    // for IE filters, removing filters re-enables cleartype 
    if (nextSlide.style.removeAttribute) 
     nextSlide.style.removeAttribute("filter"); 

    // show next slide 
    showSlide((crtSlideIndex >= totalSlides) ? 1 : crtSlideIndex + 1); 

    if (isOnSecond == true){ 
    //unhighlight all controls 
    for (var i=0; i < slidesControllersCollection.length; i++){ 
     if (slidesControllersCollection[i].className === slideHighlightClass) 
     slidesControllersCollection[i].className = ""; } 

    // highlight the control for the next slide 
    if (slidesControllersCollection[i].className === slideHighlightClass)  
    document.getElementById("slide-control-" + crtSlideIndex+1).className = slideHighlightClass; 

    isOnSecond = false; 
    } 
    isOnSecond = true; 
} 
+0

首先,我會建議將所有if語句包裝在'{}'中。但你總是在最後設置'isOnSecond'爲'true',所以這可能是問題 –

+1

謝謝你們,得到它的工作,學校的男孩錯誤:) – user2696787

+0

你需要_deperly_ indent你的代碼。問題應該是顯而易見的。 – SLaks

回答

0
if (isOnSecond == true) { 
    // do work only every second time 
    isOnSecond = false; 
} 
isOnSecond = true; 

這將始終設置isOnSecond爲真,即使你剛剛是正確的之前設置爲false。相反,使用

if (isOnSecond) { 
    // do work only every second time 
    isOnSecond = false; 
} else { 
    isOnSecond = true; 
} 

if (isOnSecond) { 
    // do work only every second time 
} 
isOnSecond = !isOnSecond; 
0

您需要'else'結尾,否則isOnSecond將始終設置爲true。

if (isOnSecond == true){ 
    //unhighlight all controls 
    //lots of code here 
    isOnSecond = false; 
} else { 
    isOnSecond = true; 
} 
+0

或者在第二個值被賦值之前退出該功能。 – Todd

0
if ($this === $that) { 
    //Logic 
    isOnSecond = false; 
} 

isOnSecond = true; 

此代碼將確保isOnSecond僅僅是一個永遠假,只要它需要解釋if語句來完成,並移動到下一個線,我可以向你保證是一個非常短的時間。

看來你應該在函數結尾處鬆開isOnSecond = true,並且只有當你真的需要它是真實的而不是總是時,纔再次聲明它是真的。

0

它看起來像你通過if語句

if (isOnSecond == true){ 
    stuff . . . 
    isOnSecond = false; 
} 

,然後設置isOnSecond爲true

isOnSecond = true; 

運行,如果你這樣做:

if (isOnSecond == true){ 
    stuff . . . 
    isOnSecond = false; 
}else{ 
    isOnSecond = true; 
} 

這將防止isOnSecond始終以「真實」出現。換句話說,如果它被設置爲true,它就會變成假,如果它被設置爲false,它就會變成真的。