首页 > 解决方案 > 在点击事件上向下滑动 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');
  });
});

标签: javascriptjquery

解决方案


工作小提琴

出现问题是因为您有两种情况,并且选择器$(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');
  });
});

推荐阅读