开发者

Can't apply .addClass to dynamically created element

I'm trying to apply .addClass to the the last item in an unordered list. The problem is, the unordered list is dynamically created from an external script. So I guess you can say, the script isn't really there until the external script constructs it. The script 开发者_运维问答seems to load this in after the page and DOM is ready.

I've tried the old basics, but to no avail:

$(function() {
    $("#svpply_items li:last-child").addClass('last');
});

$(document).ready(function() {
    $("#svpply_items li:last-child").addClass('last');
});

Any help would be hugely appreciated.


I would say make sure that all the scripts are at the bottom of you page and make sure that the ordering of external scripts is correct. If that's already the case or you've already tried that to no avail, then take a look at the $.getScript(...) function.

Something like this:

$(document).ready(function () {
    $.getScript('scripts/external.js', function (data, textStatus) {
        $("#svpply_items li:last-child").addClass('last');
    });
});


Why not try it on $(window).load(function(){.... ?


Try this:

$("#svpply_items").bind("DOMSubtreeModified", function() {
     $(this).find('li:last-child').addClass('last');
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜