繁体   English   中英

JavaScript逻辑问题

[英]Javascript logic Issue

我有一个全局变量“ isOnSecond”,最初设置为false

这连接到检测布尔值的if语句,如果为true,则执行某些操作,然后将布尔值设置回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;  
}

您最后需要一个“ else”,否则isOnSecond将始终设置为true。

if (isOnSecond == true){
    //unhighlight all controls
    //lots of code here
    isOnSecond = false;
} else {
    isOnSecond = true;  
}
 if (isOnSecond == true) { // do work only every second time isOnSecond = false; } isOnSecond = true; 

即使您之前刚将isOnSecond设置为false,也将始终将它设置为true。 相反,使用

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

要么

if (isOnSecond) {
    // do work only every second time
}
isOnSecond = !isOnSecond;
if ($this === $that) {
    //Logic
    isOnSecond = false;
}

isOnSecond = true;

这段代码将确保isOnSecond仅在一段时间内为假,只要它需要解释器完成if语句并移至下一行,我可以向您保证这是很短的时间。

似乎应该在函数末尾松开isOnSecond = true ,仅在实际需要将其设置为true而不是始终使用它时才再次声明为true。

看起来您运行了if语句

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

然后将isOnSecond设置为true

isOnSecond = true;

如果您这样做:

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

这样可以防止isOnSecond始终显示为“ true”。 换句话说,如果将其设置为true,则它将变为false;如果将其设置为false,则它将变为true。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM