jQuery检查最后三个数据属性是否相等

时间:2015-10-25 13:35:29

标签: javascript jquery

让我们说这是HTML:

<div id="chat">
  <div class="msg" data-user="7">bla</div> 
  <div class="msg" data-user="3">bla</div> 
  <div class="msg" data-user="7">bla</div>
  <div class="msg" data-user="7">bla</div>
  <div class="msg" data-user="7">bla</div> 
</div>

如何检查最后三个user attributes7

2 个答案:

答案 0 :(得分:2)

您可以将nth-last-child选择器与属性选择器结合使用:

&#13;
&#13;
var is = $('.msg:nth-last-child(-n+3)[data-user=7]').length === 3;

if (is) {
    console.log('last 3 messages has data-user 7');
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="chat">
  <div class="msg" data-user="7">bla</div> 
  <div class="msg" data-user="3">bla</div> 
  <div class="msg" data-user="7">bla</div>
  <div class="msg" data-user="7">bla</div>
  <div class="msg" data-user="7">bla</div> 
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

尝试使用.slice().get()Array.prototype.every()

&#13;
&#13;
var res = $("#chat .msg").slice(-3).get().every(function(val) {
  return val.dataset.user === "7"
});

console.log(res)
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="chat">
  <div class="msg" data-user="7">bla</div> 
  <div class="msg" data-user="3">bla</div> 
  <div class="msg" data-user="7">bla</div>
  <div class="msg" data-user="7">bla</div>
  <div class="msg" data-user="7">bla</div> 
</div>
&#13;
&#13;
&#13;