简体   繁体   English

仅使用jQuery定位下一个div

[英]Target next div only with jQuery

I'm trying to make an 'accordion' effect using jQuery. 我正在尝试使用jQuery产生“手风琴”效果。 I've managed to get it working only when my 'h5' is clicked all divs open when it should ONLY be the next div. 我设法让它仅在单击我的“ h5”时才起作用,所有div都应打开,而仅应将其作为下一个div。

$('.accordion h5').click(function() {
      $('.accordion h5').next().slideToggle('slow', function() {
        // Animation complete.
      });
});

I've made a fiddle so you can see what I mean: http://jsfiddle.net/GnAhs/1/ 我做了一个小提琴,所以您可以明白我的意思: http : //jsfiddle.net/GnAhs/1/

Inside the click function you have this: 在click函数中,您具有以下功能:

$('.accordion h5').next().slideToggle('slow', function() { ...

$( '.accordion h5' ) matches every h5 inside the .accordion div, so every one of them is toggled. $( '.accordion h5' ).accordion div中的每个h5匹配,因此它们中的每个都被切换。 Change the selector to this so that it affects only the clicked element. 将选择器更改this ,以使其仅影响单击的元素。

$('.accordion h5').click(function() {
      $( this ).next().slideToggle('slow', function() {
        // Animation complete.
      });
});

You need to make use of this : 您需要利用this

$('.accordion h5').click(function() {
    $(this).next().slideToggle('slow', function() {
        // Animation complete.
    });
});

this inside the callback function of the click event always links to the element has been clicked. this在回调函数里面click事件总是链接到元素已被点击。 So you select the clicked element and then the next element with $(this).next() . 因此,您选择了clicked元素,然后选择了带有$(this).next()的下一个元素。

Here's a working demo: http://jsfiddle.net/GnAhs/2/ 这是一个工作示例: http : //jsfiddle.net/GnAhs/2/

Just write $(this).next() instead of $('.accordion h5').next() , that matches with all .accordion h5 in the code 只需编写$(this).next()而不是$('.accordion h5').next() ,它与代码中的所有.accordion h5匹配

$('.accordion h5').click(function() {
        /*change this->*/$(this).next().slideToggle('slow', function() {
        // Animation complete.
    });
});
$('.accordion h5').click(function(){
    $(this).next("div").slideToggle('slow', function() {
        // Animation complete.
      });
});

You just need to change your selector for SlideToggle 您只需要更改SlideToggle的选择器

instead of $('.accordion h5').next().slideToggle() 而不是$('.accordion h5').next().slideToggle()

you need to specify $(this).next().slideToggle() 您需要指定$(this).next().slideToggle()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM