如何使用jQuery在每次点击中选择下一个'n'个连续元素?
在下面的示例中,我想在第一个按钮单击时选择前4个li元素,在第二个单击时选择下4个,在第3个单击时选择下一个4,最多为'n'个数字。
$(document).ready(function(){
$(".btn").on('click', function(){
$("li:nth-child(-n+4)").addClass("selected");
});
});
.btn{ text-decoration:none; background:blue; color:#fff; padding:5px; border-radius:4px;float:left;}
ul{ list-style:none;float:left;clear:both;}
ul li{ padding:5px;background:#555; color:#fff; float:left; border-radius:2px; margin:2px; }
.selected{ background:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<a class="btn">select next 4 consecutive elements</a>
<ul>
<li> 1st 4</li>
<li> 1st 4</li>
<li> 1st 4</li>
<li> 1st 4</li>
<li> 2nd 4</li>
<li> 2nd 4</li>
<li> 2nd 4</li>
<li> 2nd 4</li>
<li> 3rd 4</li>
<li> 3rd 4</li>
<li> 3rd 4</li>
<li> 3rd 4</li>
</ul>
答案 0 :(得分:2)
您可以创建一个初始化为0
的变量,并将变量增加4
,使用.slice()
选择n个元素
$(document).ready(function(){
var n = 0;
$(".btn").on('click', function(){
$("li")
.removeClass("selected")
.slice(n, n += 4)
.addClass("selected");
if (n >= $("li").length) n = 0;
});
});
&#13;
.btn{ text-decoration:none; background:blue; color:#fff; padding:5px; border-radius:4px;float:left;}
ul{ list-style:none;float:left;clear:both;}
ul li{ padding:5px;background:#555; color:#fff; float:left; border-radius:2px; margin:2px; }
.selected{ background:red;}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<a class="btn">select next 4 consecutive elements</a>
<ul>
<li> 1st 4</li>
<li> 1st 4</li>
<li> 1st 4</li>
<li> 1st 4</li>
<li> 2nd 4</li>
<li> 2nd 4</li>
<li> 2nd 4</li>
<li> 2nd 4</li>
<li> 3rd 4</li>
<li> 3rd 4</li>
<li> 3rd 4</li>
<li> 3rd 4</li>
</ul>
&#13;