如何使用jQuery从特定/所选元素中选择第n个相邻元素?
在下面的示例中,如何从选定/特定元素(<li><a href="#">this is the 2nd adjacent element from active</a></li>
)中选择第二个相邻元素(<li class="active" ><a href="#">this is the current active element</a></li>
)。
请注意:我不能使用eq()或nth-child,因为当前的活动元素会在每次鼠标点击时动态变化。
$(document).ready(function(){
$("#select").on('click', function(){
$("li").eq("2").addClass("active");
});
});
#select{ background:blue;}
ul{ list-style:none; float:left; clear:both}
ul li{float:left; clear:both;}
.active a{background:red;}
a{ color:#fff; background:#444; text-decoration:none; padding:5px; margin:2px; float:left;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="select" href="#">click to select the 2nd adjacent element from current active </a>
<ul>
<li><a href="#">111</a></li>
<li class="active" ><a href="#">this is the current active element</a></li>
<li><a href="#">333</a></li>
<li><a href="#">this is the 2nd adjacent element from active</a></li>
<li><a href="#">555</a></li>
</ul>
答案 0 :(得分:1)
如何从特定/选中的第n个相邻元素中选择 元素使用jquery
如果要选择当前活动元素的第二个下一个兄弟,可以使用nextAll()
,类似于:
$("li.active").nextAll().eq(2);
$(document).ready(function() {
$("#select").on('click', function() {
//console.log($("li.active").nextAll());
$("li.active").removeClass('active').nextAll().eq(2).addClass("active");;
});
});
#select {
background: blue;
}
ul {
list-style: none;
float: left;
clear: both
}
ul li {
float: left;
clear: both;
}
.active a {
background: red;
}
a {
color: #fff;
background: #444;
text-decoration: none;
padding: 5px;
margin: 2px;
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="select" href="#">click to select the 2nd adjacent element from current active </a>
<ul>
<li><a href="#">111</a></li>
<li class="active"><a href="#">this is the current active element</a></li>
<li><a href="#">333</a></li>
<li><a href="#">this is the 2nd adjacent element from active</a></li>
<li><a href="#">555</a></li>
</ul>
您仍然需要应用规则来确定它在结束时的行为方式,并且不会选择任何兄弟姐妹。
答案 1 :(得分:0)
您可以将eq()
与nextAll()
合并
https://api.jquery.com/nextAll/
$(document).ready(function(){
function getNthSibling(parentSelector, n)
{
return $(parentSelector).nextAll().eq(n);
}
$('#select').on('click', function() {
getNthSibling('li.active', 1).addClass('selected');
});
});
#select{ background:blue;}
ul{ list-style:none; float:left; clear:both}
ul li{float:left; clear:both;}
.active a{background:red;}
.selected a{background: green;}
a{ color:#fff; background:#444; text-decoration:none; padding:5px; margin:2px; float:left;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="select" href="#">click to select the 2nd adjacent element from current active </a>
<ul>
<li><a href="#">111</a></li>
<li class="active" ><a href="#">this is the current active element</a></li>
<li><a href="#">333</a></li>
<li><a href="#">this is the 2nd adjacent element from active</a></li>
<li><a href="#">555</a></li>
</ul>