我在网页上有一个列表。

在按下按钮后,系统将类从listFUTItem has-auction-data更改为listFUTItem has-auction-data won

我用一个mutationobserver观察该列表,并想要获取已更改的类元素的索引。

我根本不知道如何获取索引。

在该网页上,您一次只能拥有一个listFUTItem has-auction-data won。我不知道该如何切换。但这在这里并不重要。

这是一个演示:



$('.listFUTItem').click(function() {
  $(this).removeClass('listFUTItem has-auction-data');
  $(this).addClass('listFUTItem has-auction-data won');
});

var observerTest = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.attributeName === "class") {
      var attributeValue = $(mutation.target).prop(mutation.attributeName);
      if (
        attributeValue.includes("won")
      ) {
        console.log(attributeValue.index);
      }
    }
  });
});
observerTest.observe(document.body, {
  attributes: true,
  subtree: true
});

.won {
  background: #00FF00;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="paginated">
  <li class="listFUTItem has-auction-data"> Ballack</li>
  <li class="listFUTItem has-auction-data"> Lehmann</li>
  <li class="listFUTItem has-auction-data"> Pique</li>
  <li class="listFUTItem has-auction-data"> Kroos</li>
  <li class="listFUTItem has-auction-data"> Owen</li>
</ul>

最佳答案

使用jQuery可以使用$(mutation.target).index()



$('.listFUTItem').click(function() {
  $(this).addClass('won');
});

var observerTest = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log('mutation found');
    if (mutation.attributeName === "class") {
      var attributeValue = $(mutation.target).prop(mutation.attributeName);
      if (attributeValue.includes("won")) {
        console.log($(mutation.target).index());
      }
    }
  });
});

//Changed document.body to document.querySelector('.paginated') so it only observes this element (inclusing the subtree because of the settings), if you want to use jquery you can use $('.paginated').get(0).
observerTest.observe(document.querySelector('.paginated'), {
  attributes: true,
  subtree: true
});

//Try to mimic the time problem as mentioned in the comments, howver it does not seem to trigger the mutation observer which makes sense since you are listening to attribute changes only.
window.setInterval(() => { document.querySelectorAll('.time').forEach(e => e.innerText = parseInt(e.innerText) + 1)}, 1000)

.won {
  background: #00FF00;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="paginated">
  <li class="listFUTItem has-auction-data"> Ballack <span class=time>0<span>s</li>
  <li class="listFUTItem has-auction-data"> Lehmann <span class=time>0<span>s</li>
  <li class="listFUTItem has-auction-data"> Pique <span class=time>0<span>s</li>
  <li class="listFUTItem has-auction-data"> Kroos <span class=time>0<span>s</li>
  <li class="listFUTItem has-auction-data"> Owen <span class=time>0<span>s</li>
</ul>

09-17 06:45