• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • prevAll()

    获得集合中每个匹配元素的所有前面的兄弟元素,选择性筛选的选择器。

    .prevAll([selector ])
    • selector类型: Selector。一个字符串,其中包含一个选择器表达式匹配元素。

    如果提供的jQuery代表了一组DOM元素,.prevAll()方法允许我们能够通过搜索DOM树,在它们前面的元素和从匹配的元素构造一个新的jQuery对象。返回的元素顺序是从最靠近的兄弟元素开始的。

    该方法选择性地接受同一类型选择器表达式,我们可以传递给$()函数。如果选择供应,将被过滤的元素通过测试它们是否匹配。.

    考虑一个页面上有一个简单的列表:

    <ul>
       <li>list item 1</li>
       <li>list item 2</li>
       <li class="third-item">list item 3</li>
       <li>list item 4</li>
       <li>list item 5</li>
    </ul>
    

    如果我们在第三个项目开始之前,我们可以找到它面前的元素来:

    $('li.third-item').prevAll().css('background-color', 'red');
    

    此调用的结果是项目1和2的背景为红色。由于我们没有提供一个选择的表达,这些元素被明确列入前款为对象的一部分。如果我们有提供一个,这个元素将被测试的内容在匹配之前,他们都包括在内。

    例子

    Locate all the divs preceding the last div and give them a class.

    <!DOCTYPE html>
    <html>
    <head>
    <style> 
      div { width:70px; height:70px; background:#abc;
            border:2px solid black; margin:10px; float:left; }
      div.before { border-color: red; }
    </style>
    <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script>
    </head>
    <body>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    <script>$("div:last").prevAll().addClass("before");</script>
     
    </body>
    </html>
    

    上篇:prev()

    下篇:prevUntil()