javascript - 在点击事件上向下滑动 div
问题描述
我有简单的向下滑动脚本,在点击事件上显示 div。我遇到的问题是,如果我将它包装在另一个 div 中,onclick 事件将不起作用。如果可点击的 div 没有任何父 div,它可以正常工作。
我将它用于多个 div,一次只打开一个。
我需要打开 1 才能工作
HTML
<div>
<div class="clickMore">open 1</div>
</div>
<div class="clickMore">open 2</div>
<div class="showMore" style="display:none;">
<div>text</div>
</div>
JS
$(function() {
$('.clickMore').on('click', function() {
$('.showMore').not($(this).next('.showMore')).slideUp('fast');
$(this).next('.showMore').slideToggle('fast');
});
});
解决方案
出现问题是因为您有两种情况,并且选择器$(this).next('.showMore')
不会总是返回所需的结果,因为当您将.clickMore
元素放在 adiv
中时,.next()
函数将找不到该元素,因为它在当前 div 之外?
我的建议 id 添加一个条件以确保相关.showMore
元素是否直接位于单击的旁边,div
或者应该通过添加以下内容来定位它parent
:
$(function() {
$('.clickMore').on('click', function() {
if ($(this).next('.showMore').length) {
var show_more = $(this).next('.showMore');
} else {
var show_more = $(this).parent().next('.showMore');
}
$('.showMore').not(show_more).slideUp('fast');
show_more.slideToggle('fast');
});
});
条件的简短版本可能是:
$(function() {
$('.clickMore').on('click', function() {
var show_more = $(this).next('.showMore');
show_more = show_more.length > 0 ? show_more : $(this).parent().next('.showMore');
$('.showMore').not(show_more).slideUp('fast');
show_more.slideToggle('fast');
});
});
推荐阅读
- java - Java 编码风格 2019
- jquery - jquery row.siblings 无法正常工作
- prolog - 给定一个元素列表,将每个元素复制 N 次
- spring-boot - WSDL 插件 - 在 Spring Boot 中
- jquery - 如何使用 jquery 将 url 从 json 数据动态传递到 div?
- unresolved-external - 如何根据列表的总和返回符号?
- mysql - 在 Monit 中使用 --login-path 检查脚本会给出 ERROR 1045 (28000)
- java - 用于特定模式的正数和少数特殊符号验证的 Java 正则表达式
- html - 绝对定位的子 div 宽度,离开相对定位的容器
- kubernetes - 在 K8s 集群之间移动带有 PV 的 Statefulset