简体   繁体   中英

using jQuery to load php files into a div not working

so I have my main layout as such:

<div class="menu">
    <?php include('/menu.php'); ?>
</div>
<div class="main" id="content">
    <?php include('/home.php'); ?>
</div>

In the menu.php I have 4 divs set up as such:

<div class="link current">
    <a href="#" class="home">
        Home
    </a>
</div>
<div class="link">
    <a href="#" class="about">
        About
    </a>
</div>
<div class="link">
    <a href="#" class="forums">
        Forums
    </a>
</div>
<div class="link">
    <a href="#" class="contact">
        Contact
    </a>
</div>

And I'm including this.js file in the head of the index page

$(function () {
    $('div.link a').click(function () {
        $('div.link').removeClass('current');
        $(this).closest('div.link').addClass('current');
        if($('div.link a').hasClass('home')) {
            $('#content').load('/home.php');
        } else if($('div.link a').hasClass('about')) {
            $('#content').load('/about.php');
        } else if($('div.link a').hasClass('forums')) {
            $('#content').load('/forums.php');
        } else if($('div.link a').hasClass('contact')) {
            $('#content').load('/contact.php');
        } else return false;
    });
});

But it doesn't work.

I'm new to all of this and have pieced this code together using varied sources on the inte.net, after trying it myself and not being able to figure it out, I've come for help.

The hierarchy of the site is as such.

-/
    -res/
        -css/
            -default.css
        -imgs/
    -scripts/
        -jquery.js
        -load.js (this is the one shown above) 
    -index.php 
    -menu.php 
    -home.php 
    -about.php 
    -forums.php 
    -contact.php

If anyone can provide help, it will be greatly appreciated.

The first condition in your if statements is checking to see if any "div.link a" has the class "home". Therefore the first if condition is always true and you're always loading /home.php into #content. What you want to do is check to see if the link that was clicked has the class.

You should use if($(this).hasClass('home')) { ...

Also, if you want to clean things up a bit, I would suggest:

$('div.link a').click(function () {
    $('div.link').removeClass('current');
    $(this).closest('div.link').addClass('current');
    $('#content').load('/' + $(this).attr('class') + '.php');
});

This way you don't have to maintain the if statements. Though, if you end up adding more classes to those links, this will break. Perhaps use a data-* attribute? <a href="#" data-load="contact"> ...

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