让我们说这是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 attributes
是7
?
答案 0 :(得分:2)
您可以将nth-last-child选择器与属性选择器结合使用:
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;
答案 1 :(得分:1)
尝试使用.slice()
,.get()
,Array.prototype.every()
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;