Jquery 动态获取each方法中列表的大小
我试图在each中获得一个列表的大小,因为有多个列表,并且每个列表都是动态添加的。它似乎没有返回正确的号码,不知道为什么 计数应返回每个节的列表项数 这里还有一把小提琴:Jquery 动态获取each方法中列表的大小,jquery,appendto,Jquery,Appendto,我试图在each中获得一个列表的大小,因为有多个列表,并且每个列表都是动态添加的。它似乎没有返回正确的号码,不知道为什么 计数应返回每个节的列表项数 这里还有一把小提琴: 添加 拖动以确定优先级 添加 拖动以确定优先级 功能检查是否需要帮助(计数器){ 如果(计数器==2){ helperText.slideToggle(函数(){ $(this.fadeIn(); }) 如果(计数器
添加
拖动以确定优先级
添加
拖动以确定优先级
功能检查是否需要帮助(计数器){
如果(计数器==2){
helperText.slideToggle(函数(){
$(this.fadeIn();
})
如果(计数器<2){helperText.hide();};
}
}
$('.button')。每个(函数(){
var counter=$(this.parent(“form”).parent(“section”).find(“ol”).size();
控制台日志(计数器);
$(此)。单击(函数(){
如果(counter当前显示,当此脚本首次加载时,您仅运行了一次each()
函数。因此,您不应期望它拾取对DOM进行的任何动态更改
然后设置onclick函数,将计数器的值(始终是最后一个按钮的最后一个计算值)与不同的按钮进行比较。因此,本质上运行each()
后计数器有一个静态值,在单击()
。我猜这不是你想要的
您可能只需要在click()
函数中计算ol
选择的大小,因为使用此计数器
变量实际上什么也得不到
<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();