使用jQuery检查元素在DOM中是在上面还是在下面
我有以下感兴趣的DOM结构:使用jQuery检查元素在DOM中是在上面还是在下面,jquery,dom,dom-manipulation,Jquery,Dom,Dom Manipulation,我有以下感兴趣的DOM结构: <div id="portfolioItems"> <div class="portfolioItemsLine"> <div class="portfolioItem selected">1</div> <div class="portfolioItem">2</div> </div> <div class="port
<div id="portfolioItems">
<div class="portfolioItemsLine">
<div class="portfolioItem selected">1</div>
<div class="portfolioItem">2</div>
</div>
<div class="portfolioItemsLine">
<div class="portfolioItem">3</div>
<div class="portfolioItem">4</div>
</div>
</div>
1.
2.
3.
4.
每个.porfolioItem都附加了一个单击处理程序。在click handler函数中,我需要确定$('.portfolioItem.selected')是位于当前单击的portfolioItem的上方还是下方
确定中的问题是由于每两个PortfolioItem“打包”到item line Div中
如何检查所选项目的上/下位置?我建议:
$('.portfolioItem').click(
function(){
var selectedAt = $('.portfolioItem.selected').index('.portfolioItem'),
curIndex = $(this).index('.portfolioItem');
if (curIndex > selectedAt){
// the clicked item is 'later' than the .selected item in the DOM
console.log('"later"');
}
else if (curIndex < selectedAt){
// the clicked item is 'earlier' than the .selected item in the DOM
console.log('"earlier"');
}
else if (curIndex == selectedAt){
// the clicked item is the .selected item
console.log('"equal"');
}
});
$('.portfolioItem')。单击(
函数(){
var selectedAt=$('.portfolioItem.selected')。索引('.portfolioItem'),
curIndex=$(this).index('.portfolioItem');
如果(curIndex>selectedAt){
//单击的项“晚于”DOM中的.selected项
console.log(“'later'”);
}
否则如果(curIndex
参考资料:
- 我建议:
$('.portfolioItem').click(
function(){
var selectedAt = $('.portfolioItem.selected').index('.portfolioItem'),
curIndex = $(this).index('.portfolioItem');
if (curIndex > selectedAt){
// the clicked item is 'later' than the .selected item in the DOM
console.log('"later"');
}
else if (curIndex < selectedAt){
// the clicked item is 'earlier' than the .selected item in the DOM
console.log('"earlier"');
}
else if (curIndex == selectedAt){
// the clicked item is the .selected item
console.log('"equal"');
}
});
$('.portfolioItem')。单击(
函数(){
var selectedAt=$('.portfolioItem.selected')。索引('.portfolioItem'),
curIndex=$(this).index('.portfolioItem');
如果(curIndex>selectedAt){
//单击的项“晚于”DOM中的.selected项
console.log(“'later'”);
}
否则如果(curIndex
参考资料:
index()
函数,它在集合中查找元素。如果选择正确,集合的元素是一个“平面”列表(您不必担心“div/line”类):
使用index()
函数,它可以在集合中查找元素。如果选择正确,集合的元素是一个“平面”列表(您不必担心“div/line”类):
工作起来很有魅力!谢谢你,很有魅力!非常感谢。