计算介于另一个元素Jquery

时间:2019-01-13 15:12:33

标签: javascript jquery count

我有一个看起来像这样的列表:

<div class="container">
  <div class="item play">1</div>
  <div class="item do-not-play">2</div>
  <div class="item play">3</div>
  <div class="item play">4</div>
  <div class="item do-not-play">5</div>
  <div class="item do-not-play">6</div>
  <div class="item play">7</div>
</div>

如何计算每个do-not-play项之间有play类的项?

例如,如果我单击项目1,它将计算找到的do-not-play数量,直到到达项目3(返回1)。

或者,如果我单击项目4,它将返回2个do-not-play

我的问题类似于以下问题: Jquery count items between 2 elements,但问题略有不同。我没有将列表项分开的h1标签,只能播放和不播放项目。

我将如何做到这一点?谢谢。

这是另一篇文章的答案,看来我可以解决我的问题。

    $('.play').click(function () {
        alert($(this).first().nextUntil('play').length);
    });

2 个答案:

答案 0 :(得分:4)

您的问题在这里:

x-axis

您正在寻找课程,因此请使用以下内容更改上一行:

;WITH MonthsStartDates AS
(
    SELECT
        MonthStartDate = CONVERT(DATE, '2018-01-01')

    UNION ALL

    SELECT
        MonthStartDate = DATEADD(MONTH, 1, M.MonthStartDate)
    FROM
        MonthsStartDates AS M
    WHERE
        M.MonthStartDate <= '2020-01-01'
)
SELECT 
    AirlineCode,
    Year = DATEPART(YEAR, M.MonthStartDate),
    Month = DATEPART(MONTH, M.MonthStartDate),
    AppUser = COUNT(DISTINCT AppUser.Id)
FROM 
    [followme.aero.live].[dbo].[AppUser]
INNER JOIN 
    [followme.aero.live].[dbo].[UserInAppPurchase] ON AppUser.Id = UserInAppPurchase.UserId
INNER JOIN 
    MonthsStartDates AS M ON PurchaseDate < M.MonthStartDate 
                          AND ValidTo > M.MonthStartDate
GROUP BY 
    AirlineCode,
    DATEPART(YEAR, M.MonthStartDate),
    DATEPART(MONTH, M.MonthStartDate)

nextUntil('play')
nextUntil('.play')

答案 1 :(得分:0)

一种避免每次点击循环的不同方法

$(function() {
  var $lastPlayItem = "";
  var lastPlayIndex = -1;
  var $item = "";
  var $playButtons = $(".container .play");

  $.each($playButtons, function(i, item) {
    $item = $(item);
    if (i === 0) {
      lastPlayIndex = $item.index();
      $lastPlayItem = $item;
    }

    if ($item.index() > lastPlayIndex + 1) {
      $lastPlayItem.attr("data-count", $item.index() - lastPlayIndex - 1);

    }

    lastPlayIndex = $item.index();
    $lastPlayItem = $item;

  });

  $playButtons.click(function() {
    alert($(this).attr("data-count") || 0);
  });
})
.item {
  border: 1px solid green;
  margin: 5px;
}

.item.play:hover {
  cursor: pointer;
  background-color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="container">
  <div class="item do-not-play">2</div>
  <div class="item play">-1 Play</div>
  <div class="item do-not-play">2</div>
  <div class="item play">1 Play</div>
  <div class="item do-not-play">2</div>
  <div class="item play">3 Play</div>
  <div class="item play">4 Play</div>
  <div class="item do-not-play">5</div>
  <div class="item do-not-play">6</div>
  <div class="item play">7 Play</div>
</div>