简体   繁体   中英

How to toggle dynamically created div 's on the basis of class and name attributes?

I am creating Table of Content dynamically.

Hierarchy levels:

  • Parent Div

  • Children Div

    • Grand Children Div

For this I am creating div 's dynamically.

Then I am assigning margin to those divs.

Parent Div :- No margin

Children Div :- margin-left :15px;

Grand Children Div :- margin-left :35px;

So I am able to create table of content dynamically.

Problem :

I created more than one parent divs and there sub divs as per hierarchy. But If I am applying click event on first parent div then that event also getting apply on other parent div why because I am adding click event on class.

In this click I am facing problem in slideToggle(). As I am using class so because of this it is getting applied on other also.

Example:

$('main_div').haml(['%div.g', {id:'g_' + i', name: i}, Parent Div]);//class = 'g'

$('main_div').haml(['%div.g1', {id:'g_' + i, name: i, style:'**margin-left: 15px**;'}, Children Div]);//class = 'g1'

$('main_div').haml(['%div.g2', {id:'g_' + i, name: i, style:'**margin-left: 35px**;'}, Grand Children Div]);//class = 'g2'

In this div 'i' value is coming from database on with the help of AJAX GET.

So what changes should I do for slideToggle() : In this I just want to toggle only clicked parent div's childrens only?

Any hints / suggestions please?

Reference code:

$('#main_div').on('click','.g', function(){
  $('#main_div').find('.g1,.g2').slideToggle();

});

If I understand right, slideToggle() is click event for all parents div? Than in function you can use 'this' variable.

$(this).find(...some selector for child divs...').slide..

Show, please, code for click event?

Try this:

$('#main_div').on('click','.g', function(){
   $(this).find('.g1,.g2').slideToggle();
});

When jQuery calls your click handler it sets this to the clicked item, ie, to the .g element, so only apply .find() to that item's descendants by using $(this).find(...

Following Reference Link solved my problem.

On click slidetoggle div but hide others first - jQuery

Thanks to other people also.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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