当所有元素都添加了类时,我需要显示警报
html
<ul class="container">
<li class="box"> </li>
<li class="box"> </li>
<li class="box"> </li>
</ul>
jquery-
$(document).ready(function() {
$('.box').click(function() {
$(this).addClass('Boxaddedclass');
});
});
单击每个框后,“Boxaddedclass”类将添加到每个列表中,类为“.box”。
jquery-
$(document).ready(function () {
$(".box").click(function () {
if($(".box").hasClass("Boxaddedclass")) {
alert('all boxes have the added class')
}
});
目前,在我单击每个单独的 Box 类后,每次都会出现警报,我需要当所有这些都具有添加的类而不是单独的时出现警报。有办法解决这个问题吗?
最佳答案
比较 .box
与 .Boxaddedclass
类的元素数量
var boxCount = $(".box").length;
var addedBoxClass = $(".Boxaddedclass").length;
if (boxCount === addedBoxClass) {
alert("All boxes have added the class"); //note that I don't support alert, you really should console.log it, or do something fancier
}
关于javascript - 当具有相同类名的多个元素添加了类时发出警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39802407/