Pregunta

I have a personnal function which load a file and I want after loading the page changing a class.

The function is

var _loadFile = function(filename, container, errorMessage) {
    $.ajax({
        url : filename,
        type: "GET",
        cache: false,
        dataType: "html",
        success : function (data) {
            $(container).html(data);
        }
    });
}

When I want to use it I do

_loadFile('assets/data/html/file.html', '#containerID', 'errorMessage');
$(idActive).addClass('active');

The file is loaded but the class is not changed. And as I want a generic function I can't change the class in the success().

Thanx for your help

¿Fue útil?

Solución

You are trying to modify DOM (addClass) of the element that is not yet loaded. Try this approach instead:

var _loadFile = function(filename, container, errorMessage) {
    return $.ajax({
        url : filename,
        type: "GET",
        cache: false,
        dataType: "html",
        success : function (data) {
            $(container).html(data);
        }
    });
}

_loadFile('assets/data/html/file.html', '#containerID', 'errorMessage')
.then(function() {
    $(idActive).addClass('active');
});

$.ajax returns promise object, and you use then method of it. You could also move $(idActive).addClass('active'); inside success callback, but it's not nice: I assume that _loadFile is a generic function and we don't want it to be aware of anything else but loading data.

Otros consejos

You have to add the class on the success callback if the element "idActive" is loaded via AJAX:

var _loadFile = function(filename, container, errorMessage) {
    $.ajax({
        url : filename,
        type: "GET",
        cache: false,
        dataType: "html",
        success : function (data) {
            $(container).html(data);
            $(idActive).addClass('active');
        }
    });
}

assuming that idActive is defined and generated. Otherwise add an

console.log($(idActive));

and look at the console output to be certain, that the element you want to add the class really exists.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top