【问题标题】:Check if the element is above or below in the DOM with jQuery使用 jQuery 检查元素在 DOM 中是高于还是低于
【发布时间】:2012-06-19 22:55:34
【问题描述】:

我有以下感兴趣的 DOM 结构:

<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>

每个 .porfolioItem 都附加了一个点击处理程序。在单击处理程序函数中,我需要确定 $('.portfolioItem.selected') 是位于当前单击的投资组合项上方还是下方。

确定的问题是由于每两个portfolioItems被“打包”到项目行div中。

如何检查 .selected 项目的上/下定位?

【问题讨论】:

    标签: jquery dom dom-manipulation


    【解决方案1】:

    我建议:

    $('.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"');
            }
        });​
    

    JS Fiddle demo.

    参考资料:

    【讨论】:

    • 像魅力一样工作!谢谢。
    【解决方案2】:

    使用index() 函数,它在集合中找到一个元素。如果选择正确,集合的元素是一个“平面”列表(您不必担心“div/line”类):)

    $(".portfolioItem").click(
        function()
        {
            var items = $("#portfolioItems .portfolioItem");
            var selected = $("#portfolioItems .selected");
            var i = $(items).index(selected);
            var j = $(items).index(this);
            console.log(i,j);
            // compare i and j to understand if above or below
        }
    );​
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-02
      • 2023-03-27
      • 1970-01-01
      • 2014-11-14
      • 2011-03-25
      • 1970-01-01
      相关资源
      最近更新 更多