代码之家  ›  专栏  ›  技术社区  ›  reto

选择两个p元素之间的所有元素

  •  0
  • reto  · 技术社区  · 16 年前

    我正在寻找一种很好的方法来标记/选择两个选定元素之间的所有元素。

    想象

    <parent>
      <p>...</p>
      <p>...</p>
      <p>...</p>
      <p>...</p>
    </parent>
    

    父对象上有一个单击处理程序。用户现在可以在这个列表中选择两个p元素,然后中间的所有p元素都应该被激活。

    我在考虑这样一个系统:

    1. 确定A是否在B之前

    我不知道怎么做3,除了蛮力方法(在两个方向迭代,看看它是否存在)

    • dom内部是否知道哪个元素在另一个元素之前?

    关于我的情况:父母可能有几千个p。

    雷托

    3 回复  |  直到 16 年前
        1
  •  5
  •   James    16 年前

    要确定哪个元素首先出现,只需执行以下操作:

    $(a).index() < $(b).index()
    

    或者,稍微快一点的方法:

    $(a).prevAll().length < $(b).prevAll().length
    

    a 和 b


    天气怎么样 <p> p1 , p2

        2
  •  1
  •   Anurag    16 年前

    compareDocumentPosition 在domlevel3中定义,用于比较两个DOM节点的位置。

    您可以将其用作:

    firstPara.compareDocumentPosition(otherPara);
    

    如果返回值为 2 Node.DOCUMENT_POSITION_PRECEDING firstPara 在前面 otherPara .

    还有一个 jQuery plugin 为了它。

    <parent>
      <p data-pos="1">..</p>
      <p data-pos="2">..</p>
      ..
    </parent>
    

    访问方式 $(e).attr('data-pos')

        3
  •  1
  •   ipopa    16 年前

     <div id="test">
              <p>abc</p>
              <p>def</p>
              <p>ghi</p>
              <p>jkl</p>
            </div>
    
        <script>
        var a = $('#test').find('>p');
        var cli = [], range;
        $('#test').delegate("p",'click', function(event){
                if (cli.length < 2){//if there are less than 2 clicks in the queue
                  cli.push(a.index(event.target));
                }
                else{//reset queue and recall the function
                    cli = [];
                    arguments.callee(event);
                }
    
                if (cli.length == 2){//if there are 2 clicks
                 //filter from the initial selection only the elements between the two clicks
                 range = a.filter(":lt("+cli[1]+"):gt("+cli[0]+")");
                 if (cli[0]<cli[1]) {//aply some style to highlight and then revert
                  range.css({color:'red'});
                  setTimeout(function(){range.css({color:'black'})}, 1000);
              }
                }
        });
        </script>