删除jquery中某个位置之后的所有容器



我有一个过程,它根据对问题的回答添加div容器。用户可以选择在任何时候重新开始。我想在用户这样做的某个时间点之后删除所有容器。例如,以下是您在3个回复后会看到的内容。

<div id="SolutionAdvisor">
    <div id="Col1"><div class="content">some content here</div></div>
    <div id="Col2"><div class="content">some content here</div></div>
    <div id="Col3"><div class="content">some content here</div></div> 
 </div>

如果用户决定回到问题2,这是我想看到的:

  <div id="SolutionAdvisor">
    <div id="Col1"><div class="content">some content here</div></div>
    <div id="Col2"><div class="content">some content here</div></div> 
 </div>

我试过使用:gt索引,比如:

     $('#SolutionAdvisor div:gt('+column+')').remove();

也尝试过:

     $('#SolutionAdvisor div:gt('+column+')').each(function(){$(this).remove();});

其中列将是1。

相反,我看到的是这样的东西:

 <div id="SolutionAdvisor">
    <div id="Col1"><div class="content">some content here</div></div>
    <div id="Col2"><div class="content">some content here</div></div>
    <div id="Col2"><div class="content">some content here</div></div> 
 </div>

做这件事的正确方法是什么?

您可以从父div中获得子级列表,作为html元素的数组。然后,将每一个都封装在一个jQuery调用中,并按如下方式删除它们:

var maxQuestions = 2;
 children = $('#SolutionAdvisor').children();
 for (var i = maxQuestions; i < children.length; i++) {
     $(children[i]).remove();
 }

Fiddle:http://jsfiddle.net/stevenmtwhunt/YQusg/2/

使用jQuery选择器也有一些很酷的方法,我只是喜欢for循环在概念上的简单性。

您应该使用直接子代选择器,如:

$('#SolutionAdvisor > div:gt(?)).remove():

还要注意,传递给gt()的值是零索引的。

此外,您可能希望对这些div进行分类,以便可以直接访问它们,如:

$('.responses:gt(?)').remove();

这是使用.nextAll()方法捕获输入值之后的所有元素的最佳场景。。

$('#txt1').on('change' , function() {
        var quesNo = $(this).val();    
        $('#SolutionAdvisor div:nth-child('+quesNo+')').nextAll().remove();        
    });

在此处检查FIDDLE

相关内容

最新更新