简体   繁体   中英

jQuery loading content in div onClick

I have pages in my 'inc' folder, when I hit the 'trigger', #wrapper will load the selected page into the #wrapper. The problem I have is;

Whenever I click on 'trigger' outside of the #wrapper it works. And the content will load into the #wrapper. But when I have the 'trigger' inside of the #wrapper it won't work.

I'm stuck on this for a while.

The JS code:

$(document).ready(function() {

    // Initial
    $('#wrapper').load('inc/home.php');
});

$(document).ready(function() {

    // Set trigger and container variables
    var trigger = $('#test a'),
        container = $('#wrapper');

    // Fire on click
    trigger.click(function() {
        var target = $(this).attr('href'); 

        // Begin fade
        setTimeout(function(){ $('#wrapper').css("opacity", "0"); }, 0);

        // Load target page into container
        setTimeout(function(){ container.load('inc/' + target + '.php'); }, 400);

        // End fade
        setTimeout(function(){ $('#wrapper').css("opacity", "1"); }, 900);

        // Stop normal link behavior
        return false;
    });
});

It is because the element was not available, hence, the event was never binded. You can try following using jQuery.load callback.

$(document).ready(function() {
  var container = $('#wrapper');
  container .load('inc/home.php', function() {
    var trigger = $('#test a');

    trigger.click(function() {
      // your code here
    });
  });
});

Alternatively, you can use jQuery.on for dynamic elements

Update from

trigger.click(function() {

to

container.on("click", "#test a", function() {

Maybe you should post your DOM/Html file also... Probably its a problem with the selection of the trigger. Try to select it with a class:

<a class="trigger-button">Click Me</a>


var trigger = $('.trigger-button')

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