开发者

A function instead of the sibling function

开发者 https://www.devze.com 2023-03-02 20:06 出处:网络
I want to know is there a function which can be used instead of the sibling function. I am asking for this because the sibling function requires them to be in the same div for instance and this at tim

I want to know is there a function which can be used instead of the sibling function. I am asking for this because the sibling function requires them to be in the same div for instance and this at times is messing my layout. What function can I use instead? Ill post an example code below.

   <div class='hey'> 
   <div class='yes'><button class='my'> </button> </div> 
   <div class='what'> </div>
   </div>


  <div class='hey'> 
  <div class='yes'><button class='my'> </button> </div> 
  <div class='what'> </div>
  <div>

I want to slide down the div class What independently depending on where the button is clicked. Any help is appreciated thanks! Please kindly post a开发者_开发知识库n example and explain the function cheers!


In this case you could use something like:

$('button').click(
    function(){
        $(this).closest('.hey').find('.what').slideToggle();
    });

JS Fiddle demo.


Edited because I completely forgot to 'explain the function.' Oops.

  1. $('button').click( selects html button elements, and attaches the jQuery click-handler to them.
  2. $(this).closest('.hey').find('.what').slideToggle() effectively starts at the this element (the button), moves upwards in the ancestry until it finds the closest element that matches the selector that matches the selector-string, an element of class-name .hey, and then, within that element's descendants looks for an element of class-name .what. After finding this element it slideToggle()s its visibility; showing it if it's hidden, hiding it if it's visible.

References:

  • click().
  • closest().
  • find().
  • slideToggle().
0

精彩评论

暂无评论...
验证码 换一张
取 消