gpt4 book ai didi

javascript - 获取最后5个数据属性并检查它们是否相同

转载 作者:行者123 更新时间:2023-11-28 12:14:41 26 4
gpt4 key购买 nike

这是 HTML:

<div class="message" data-userid="7">tada</div>
<div class="message" data-userid="7">tada</div>
<div class="message" data-userid="7">tada</div>
<div class="message" data-userid="7">tada</div>
<div class="message" data-userid="8">tada</div>
<div class="message" data-userid="7">tada</div>
<div class="message" data-userid="7">tada</div>

我需要查明最后 5 个 userid 是否相同,在本例中是不同的。我怎样才能用 jQuery/Javascript 做到这一点?

我所知道的只是如何获得第一个和最后一个:

var firstid = parseInt($(".message:first").attr("userid"));
var lastid = parseInt($(".message:last").attr("userid"));

但我需要最后 5 个..

最佳答案

详细信息在下面的代码中注释:

const initialUsers = [...document.querySelectorAll("[data-userid]")]; // Elements with data-userid attributes

console.log(initialUsers.length); // initial length

const users = initialUsers.slice(initialUsers.length-5); // Slicing for last 5 elements

console.log(users.length); // checking length

const referenceUserId = users[0].dataset.userid; // taking value of data-userid as reference

const allAreSame = users.every( user => user.dataset.userid === referenceUserId ); // checking if all the 5 elements have same value for data-userid attribute

console.log(allAreSame); // If last 5 are same retuns true otherwise false
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="message" data-userid="7">tada</div>
<div class="message" data-userid="7">tada</div>
<div class="message" data-userid="7">tada</div>
<div class="message" data-userid="7">tada</div>
<div class="message" data-userid="8">tada</div>
<div class="message" data-userid="7">tada</div>
<div class="message" data-userid="7">tada</div>

关于javascript - 获取最后5个数据属性并检查它们是否相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52043149/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com