سؤال

I have a main html page that loads other html pages into a div using jQuery. Like this:

$('.controlPanelTab').click(function() {
    $(this).addClass('active').siblings().removeClass('active');

    var name = $(this).attr('name');

    //create the html doc name + append it to the displayPanel Div
    var docName = name + ".html";
    $("#displayPanel").load(docName);

});

The page displays correctly, references the correct style sheet etc. so far so good.

However, an issue arises when it comes to interacting with the loaded page (inside the div). For instance, one of the loaded pages has a text area, that focuses on click, but does not allow text to be entered. Another page uses jQuery to animate some statistics on screen. Accessing that page directly in the URL bar shows the statistics animating correctly, but once loaded into the div using the above method, no animation occurs.

It's as though the main page does not recognise the loaded page because it was set too late, and perhaps loading everything in one go at the start would get around this issue. But if possible I would prefer to adopt a lazy-loading approach, and keep these "sub" html pages separate.

Is there any way of refreshing the main page (the DOM?) so that it recognises the new elements correctly (if this is indeed the issue)?

EDIT Code that worked:

$(document).on('click', '.controlPanelTab', function() {

$(this).addClass('active').siblings().removeClass('active');

var name = $(this).attr('name');

//create the html doc name + append it to the displayPanel Div
var docName = name + ".html";
$("#displayPanel").load(docName);

//create external .js file name and call it up
docName = name + ".js";
$.getScript(docName, function( data, textStatus, jqxhr ) {

    if (textStatus==="success") {
            lightItUp(); //load method
    }
});
});
هل كانت مفيدة؟

المحلول

You will need to reload js scripts referenced in newly loaded .html file; I also had this issue and I used $.getScript() API to reload JS scripts. load() has success-handler that you can use as follows-->

$('#Target').load(docName, function(data, status, xhr) {
if( status === 'success' ) 
{                        
    $.getScript("JSFileName", function(data, textStatus, jqxhr) 
    {          
    }
}

نصائح أخرى

You may want to replace:

$('.controlPanelTab').click(function() {

with

$(document).on('click', '.controlPanelTab', function() {

Ref: https://api.jquery.com/on/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top