2011-07-15 158 views
1
$('.HelpBoxOk').live('click',function() 
{ 
    var BoxHelpMain = $(this).parent().parent().parent().parent().parent().parent(); 

    var ShouldFadeIn = false; //if the button says next then there is more divs to fadein if it says ok then no more divs to fade in i.e end of divs 
    if($(this).attr('value') == 'Next') 
    { 
     ShouldFadeIn = true; 
    } 

    BoxHelpMain.fadeOut().queue(function() //fadeout the current div 
    { 
     if(ShouldFadeIn == true) // if it should fade in next div 
     { 
      FadeinNextDiv = false; 
      AllBoxHelpMain = $(document).find("[id^=BoxHelpMain]"); // find all div with the same id as current one 

      if(AllBoxHelpMain.length) // if any divs with id exists 
      { 
       AllBoxHelpMain.each(function() // loop through all the divs 
       { 
        if(FadeinNextDiv == true) // if we need to fade in the next div 
        { 
         $(this).fadeIn(); 
        $(this).find("input[class^=HelpBoxOk]:first").focus();  // fade in the div   
         FadeinNextDiv = false; 
         return false; 
        } 
        if($(this).attr('id') == BoxHelpMain.attr('id')) // if current div id matches the clicked box/div then the next box/div needs to be fadded in 
        {      
         FadeinNextDiv = true; 
        } 
       })   
      } 
     } 
    }); 
    return false; 
}); 

請幫我糾正這個蹩腳的代碼。我的要求是有很多div,其ID以BoxHelpMain開頭,有一個按鈕HelpBoxOk。現在,點擊helpBoxOk,我希望它在整個文檔中搜索下一個BoxHelpMain,然後淡出當前的BoxHelpMain並淡化下一個BoxHelpMain。如果沒有其他分區存在,則只是淡出論文的div是兄弟的當前jquery淡入淡出幫助

無和散落在DOM

+2

出於好奇,誰寫了的代碼?大聲笑。雖然它肯定可以調整爲optmisation,提供它的工作,這不是那麼糟糕_believe me_。那裏有各種各樣的東西。 POST-EDIT:在重新讀取代碼後,在第3行,我意識到它是,那麼糟糕 – stefgosselin

+1

您的_crappy_ HTML在哪裏? – Shef

回答

3

首先,給你所有的BoxHelpMain*的div的同一類:

<div id="BoxHelpMain1" class="boxhelp"> 

假設所有這些元素都在相同級別的DOM層次結構中(即他們都是兄弟姐妹)找到下一個然後縮小爲:

var current = $(this).closest('.boxhelp');   // find button's parent 
var next = $(current).nextAll('.boxhelp').first(); // find next .boxhelp 

而且你的衰落只是變成:

$(current).fadeOut(function() { 
    $(next).fadeIn(); // called when the .fadeOut() completes 
}); 

有沒有必要檢查next是否存在 - jQuery將忽略空列表。

如果他們不姐弟,試試這個:

var $current = $(this).closest('.boxhelp'); // find button's parent 
var $next = $();        // an empty jQuery object 

var $all = $('.boxhelp'); 
for (var i = 0; i < $all.length - 1; ++i) { 
    if ($all.get(i).is($current)) { 
     $next = $all.get(i + 1); 
     break; 
    } 
} 

然後如上淡出。

+0

這些div都不是兄弟姐妹,而是分散在各個角落 – aWebDeveloper