Mario S
Mario S

Reputation: 1984

jQuery event click in nested divs

I got a page that loads content dynamically.

This is the resumed HTML code generated by page_ONE.php

<body>
<script type="text/javascript">
    $(document).ready(function() {
    $(document).on('click', "#contentarea_ONE a", function(ev) { 
            ev.preventDefault();
            ev.stopPropagation();
            ev.stopImmediatePropagation();
            $('#contentarea_ONE').load($(this).attr('href'));
            return false;
    });
    });
</script>
<div id="contentarea_ONE">
</div>
</body>

I have the ALMOST SAME code for page_TWO.php and page_THREE.php, just changing ONE for TWO or THREE wherever it corresponds.

I have buttons in each page that permits me to load page_TWO.php inside #contentarea_ONE, and page_THREE.php inside #contentarea_TWO.

Firebug shows me this as the HTML in navigator memory:

<body>
<script type="text/javascript">
    $(document).ready(function() {
    $(document).on('click', "#contentarea_ONE a", function(ev) { 
            ev.preventDefault();
            ev.stopPropagation();
            ev.stopImmediatePropagation();
            $('#contentarea_ONE').load($(this).attr('href'));
            return false;
    });
    });
</script>
<div id="contentarea_ONE">

<div id="contentarea_TWO">

<div id="contentarea_THREE">

</div>
</div>
</div>
</body>

Well, this is the problem: when I have the three pages loaded in that nested way, when I click a link like <a href="xxx/yyy"> inside div #contentarea_THREE, although I would expect the content loads inside contentarea_THREE, the content is loaded inside the div #contentarea_TWO.

Why does that occur?

Upvotes: 1

Views: 1565

Answers (1)

Jai
Jai

Reputation: 74738

You can try with this:

$(document).ready(function() {
    $(document).on('click', '[id^="contentarea_"] a', function(ev) { 
        ev.preventDefault();
        ev.stopPropagation();
        $(this).closest('[id^="contentarea_"]').load($(this).attr('href'));
    });
});

See first of all all your divs are starting with same id initials or i might say they have contentarea_ in common. so try using attr selectors and when you are clicking the links inside this div then try finding out the closest div with same id initials $(this).closest('[id^="contentarea_"]') and perform the load.

Upvotes: 2

Related Questions