2013-05-31 29 views
0

我想獲取每個列表中的列表大小,因爲有多個列表,每個列表都被動態添加。它似乎沒有返回正確的數字,不知道爲什麼。動態獲取每個方法中的列表大小

計數應返回的每節

也有一個小提琴在這裏設置列表項的數目:http://jsfiddle.net/Dqf8B/

<section id="questionOne"> 
       <span class="surveyQuestion"></span> 
       <form> 
        <input> 
        <a class="button">Add</a> 
       </form> 
       <p class="helperText">drag to prioritize</p> 
       <ol class="draggable answers"> 
       </ol> 
      </section> 

      <section id="questionTwo"> 
       <span class="surveyQuestion"></span> 
       <form> 
        <input> 
        <a class="button">Add</a> 
       </form> 
       <p class="helperText">drag to prioritize</p> 
       <ol class="draggable answers"> 
       </ol> 
      </section> 

function checkIfHelperIsNeeded(counter) { 
    if(counter == 2){ 
     helperText.slideToggle(function(){ 
      $(this).fadeIn(); 
     }) 
    if (counter < 2) { helperText.hide(); }; 
    } 
} 

$('.button').each(function(){ 
    var counter = $(this).parent("form").parent("section").find("ol").size(); 
    console.log(counter); 
    $(this).click(function(){ 
     if(counter <= 5) { 
      checkIfHelperIsNeeded(counter); 
      var myCurrentInputTags = $(this).parent('form').children('input').val(); 
      var li = $('<li class="tag">'+myCurrentInputTags+'</li>'); 
      $('<span class="close"></span>').on('click', removeParent).prependTo(li); 
      $(this).parent('form').parent('section').children('.draggable').prepend(li); 
     } else { alert("only 5 answers per question allowed")} 
    }); 
}) 

function removeParent() { 
    $(this).parent().fadeOut(function() { 
     $(this).remove(); 
    }); 
} 

var helperText = $(".helperText"); 
helperText.hide(); 

回答

0

目前似乎正在運行的each()功能只有一個時候,這個腳本第一次加載。因此,您不應該期望它能夠動態獲取對DOM做出的任何更改。

然後,您可以設置一個onclick函數來比較counter值(它總是最後一個按鈕的最後計算值)與可能是不同按鈕的值。因此,在運行each()之後,counter具有一個靜態值,在click()期間將對所有按鈕進行比較。我猜這不是你想要的。

您應該只計算click()函數中ol選擇的大小,因爲使用此counter變量確實沒有獲得任何結果。