Search code examples
jqueryhrefinnerhtml

jQuery content loaded via .load() but href link not working


I have a problem with HTML content loaded with .load(). I have an 'accordion' menu that is working great, and on clicking an item in the menu there's a small jquery code used to load the required content into the assigned [div]

The problem I'm having is that on some of the pages that are loaded there are some href="" links. Clicking these links does not cause the 'next' page to load into the div, but instead actually forces a reload of the main page (as though you'd just pressed the RELOAD button on the browser)...

menu.js (snipped)

$(document).ready(function() {
    $(".Page1").click(function () {
        $("#pageloadarea").load('Page1.php');
        $('head').append(
            '<link rel="stylesheet" href="includes/style.css" type="text/css" />'
        );
        return false;
    });

    $(".Page2").click(function () {
        $("#pageloadarea").load('Page2.php');
        $('head').append(
            '<link rel="stylesheet" href="includes/style.css" type="text/css" />'
        );
        return false;
    });
});

Menu Section (snipped) from index.php page

<ul>
  <li class="button"><a href="" class="Page1">Page1</a></li>
  <li class="dropdown">
    <ul>
      <li><a href="" class="Page2">Page2</a></li>
      <li><a href="" class="Page3">Page3</a></li>
      <li><a href="" class="Page4">Page4</a></li>
    </ul>
  </li>
</ul>

In the index.php page the menu is located inside [div id="menu"] and the content is injected/loaded into [div id="pageloadarea"]

Clicking on Page1 in the menu successfully loads Page1.php into the [div], as does clicking Page2, Page3 and Page4 (from the menu)...

Once Page1.php has been loaded into the [div] there is a standard link

<a href="" class="Page2">Page 2</a>

This is the link that does not work. I have numerous sub-pages that have [a href] links within them and none of them work once the main content has been through the .load() process...

Any assistance would be appreciated!


Solution

  • $(document).ready(function() {
        $(document).on("click",".Page1", function () {
            $("#pageloadarea").load('Page1.php');
            $('head').append(
                '<link rel="stylesheet" href="includes/style.css" type="text/css" />'
            );
            return false;
        });
    
        $(document).on("click",".Page2", function () {
            $("#pageloadarea").load('Page2.php');
            $('head').append(
                '<link rel="stylesheet" href="includes/style.css" type="text/css" />'
            );
            return false;
        });
    });
    

    Use this as it will bind the event to new loaded DOM elements also.