gpt4 book ai didi

javascript - 循环遍历元素列表以查看它们是否处于事件状态

转载 作者:行者123 更新时间:2023-12-02 23:25:07 24 4
gpt4 key购买 nike

我有一个元素列表 ( <li> ),其中有两个特定的 <li>共享一个类( .example ),我想检查当任何此元素处于事件状态(具有类 .active )时,应该出现一个弹出窗口。

在切换类 .active 的单击事件中,我添加了一个循环来检查是否有任何 <li> elements 有这两个类,但我似乎无法使其正常工作。

$('ul li').click(function() {
$(this).toggleClass('active');

$("ul li").each(function() {
if($(this).hasClass('example') && $(this).hasClass('active')){
$('.pop-up').css("display", "block")
} else {
$('.pop-up').css("display", "none")
}
})
});

如果一个或两个元素具有类 .example 和 .active,则应出现弹出窗口。

最佳答案

下面的示例将按照您的意愿运行。

问题 -我认为您的代码的问题在于,根据定义,您的某些元素缺少类 .example.active ,因此在您激活示例的情况下,它将显示模式,但在循环浏览所有其他列表项时再次隐藏它。

方法一 - 调整您的代码并使其更加高效,检查 li 是否存在。两个类 .active.example

方法二 - 稍微快一点,因为它只是假设对 li.example 的任何点击元素应该显示弹出窗口(这可能是您期望的用户体验,因为弹出窗口不太可能通过单击 li 的过程关闭,而是通过其自己的关闭按钮或类似按钮关闭)

正如 @Hackbyrd 所提到的 - 如果您正在动态加载这些 li,您可能希望将事件监听器放置在父 DOM 元素上元素(即页面加载时它们不存在)。

我添加了一些样式来帮助了解发生了什么。 .active元素带有下划线。

如果这不是您所希望的,请告诉我。

<小时/>

演示

// METHOD ONE
// Add click event to list items
$('ul li').click(function() {

// Add active class to clicked list element
$(this).toggleClass('active');

// Check if .example.active exists
// i.e. length of array is greater than 0
if ($("ul li.example.active").length > 0) {
$('.pop-up').css("display", "block")
} else {
$('.pop-up').css("display", "none")
}

});


// METHOD TWO
// Add click event to second example
$('ul li.example2').click(function() {

// Show pop-up
// This assumes that .active class is not needed for any other reason
// And that the modal is closed via a different method (i.e. a close button within the modal, which is typical for a modal)
$('.pop-up').show();

});


// Shouldn't be necessary, your modal should have a closing method already
// Only for demo purposes
$("a.close-pop-up").click(function() {
$('.pop-up').hide();
});
.pop-up {
display: none;
border: 1px solid black;
padding: 20px;
}

.example {
color: blue;
}

.example2 {
color: green;
}

li.active {
text-decoration: underline;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>Not an example list item</li>
<li class="example">An example list item</li>
<li class="example2">An example list item - METHOD 2</li>
<li class="example">An example list item</li>
<li class="example2">An example list item - METHOD 2</li>
<li>Not an example list item</li>
</ul>

<div class="pop-up">
<p>Pop-up</p>
<a class="close-pop-up">Close</a>
</div>

关于javascript - 循环遍历元素列表以查看它们是否处于事件状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56774662/

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