views:

53

answers:

4

Hello.

What is the best way to do this dynamic events linking between divs in jquery.

my HTML page:

<html>
<body>
<div id="parent1"></div>
<div id="parent2"></div>
<div id="parent3"></div>
<div id="child1"></div>
<div id="child2"></div>
<div id="child3"></div>
</body>
</html>

for each clicked parent i want to .toggle its child

Example :: if parent2 clicked, .toggle will be applied on child2 only

my parents and childs divs are dynamically created so their number is not static, i think .live should be used here, but i have no idea how to achieve that.

Thanks

A: 

This should do it, using the rel attribute to note link. You could also do the same thing by parsing the ID and so on, but I find this solution more semantic (if it means something) :

<html>
<body>
<div id="parent1" class="parents" rel="child1"></div>
<div id="parent2" class="parents" rel="child2"></div>
<div id="parent3" class="parents" rel="child3"></div>
<div id="child1"></div>
<div id="child2"></div>
<div id="child3"></div>
</body>
</html>

jQuery(function(){
  jQuery(".parents").live("click", function(){
     jQuery("#"+jQuery(this).attr("rel")).toggle();
  });

});
marcgg
A: 

Use a class for these divs and use the class selector.

$(".divclass").live ( "click" , function() {
    $(this).find("yourchildelementselector").toggle();
});

If its a parent child relation then better put the child divs inside the parent element.

<div id="parent1" class="parent"><div id="child1" class="child"></div></div>
<div id="parent2" class="parent"><div id="child2" class="child"></div></div>
<div id="parent3" class="parent"><div id="child3" class="child"></div></div>

and you can call the click event as

$("div.parent").live ( "click" , function() {
        $(this).find("div.child").toggle();
});
rahul
A: 

This will work with your current structure (another option is to extract the number, same general idea):

$("[id^=parent]").live('click', function(){
   var childId = this.id.replace('parent', 'child');
   $('#' + childId).toggle();
});
Kobi
A: 

Using the startsWith selector and slightly modded ID values, because the underscore character eliminates the need for a regex:

<div id="parent_1" class="parents"></div>
<div id="parent_2" class="parents"></div>
<div id="parent_3" class="parents"></div>
<div id="child_1"></div>
<div id="child_2"></div>
<div id="child_3"></div>

$("div[id^=parent]").click(function() {
   $('#child_' + $(this).attr('id').split('_')[1]).toggle(); 
});

I also like @Kobi's approach.

karim79