如果.next()元素是.last()元素? [英] If .next() element is the .last() element?
问题描述
我知道这很简单,但是.next()
和.last()
有点使我感到困惑.我有点不知所措.
I know it's quite simple, but .next()
and .last()
kind of confuse me. I'm kind of mixed up.
本质上我想做的是,当下一个元素是列表中的最后一个元素时,添加一个类.
What I am essentially trying to do is add a class when the next element is the last of the kind in a list.
Fiddle
在我当前的代码中,它在显示最后一个元素后又回到第一个元素时添加了该类.
In my current code it adds the class after the last element is displayed, when it goes back to the first.
jQuery: 我确定它与.length
$("#next-button").on('click', function () {
var nextItem = $('.active').removeClass('active').next(),
breadItem = $('.clickable').next();
if (!nextItem.length) {
nextItem = $('.item').first();
//Here I try to add class ".last" to the last ".item" element
$('.item').last().addClass('last');
}
nextItem.addClass('active');
breadItem.addClass('clickable');
});
当您单击最后一个元素并返回到第一个元素时,这将添加类.
This adds the class when you click on the last element going back towards the first.
还有一个额外的问题,我为什么将类.clickable
添加到面包屑时感到困惑,只有第一个将我带到右侧data-id
选中
Also for a bonus question, I am confused as to why when I add class .clickable
to the breadcrumbs only the first one takes me to the right data-id
check the Fiddle
我非常感谢这个社区以及我所获得的所有帮助,对于jQuery专家来说,这将非常容易,感谢您的学习帮助.
I appreciate this community and all the help I am getting, for a expert in jQuery this will be quite easy, thanks for helping me learn.
推荐答案
首先要解决的问题
$("#next-button").on('click', function () {
var nextItem = $('.active').removeClass('active').next(),
breadItem = $('.clickable').next();
if (!nextItem.length) {
nextItem = $('.item').first();
$('.item').last().addClass('last');
}
nextItem.addClass('active');
breadItem.addClass('clickable');
// 1st Req
// Remove the last class for items
$('.item').removeClass('last');
var last = $('.item').last();
// Check if the item is the last one
// it true add last and remove active
if(nextItem.is(last)) {
nextItem.addClass('last').removeClass('active');
}
});
2nd需要事件委托,因为它是动态添加的元素
2nd requires event delegation since it's a dynamically added element
更新
$(".breadcrumbs").on('click', '.clickable .breadcrumb', function () {
$('.active').removeClass('active');
var theID = $(this).data("id");
var selectedItem = $("#" + theID);
selectedItem.addClass('active');
$('.item').removeClass('last');
var last = $('.item').last();
if(selectedItem.is(last)) {
selectedItem.addClass('last').removeClass('active');
}
});
这篇关于如果.next()元素是.last()元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!