在ie8中使用jQuery函数向动态追加的元素添加类

时间:2014-01-08 10:49:28

标签: javascript jquery css internet-explorer-8 addclass

尝试了一些没有运气的选择。我正在使用jQuery 1.9.1

这是我的函数代码:

(function ($) {
    $.fn.createGallery = function(options) {
        var theObject = $(this);
        var settings = $.extend({
            // These are the defaults.
            server: 'http://localhost/jQuery%20Gallery/images/galleries/',
            galleryName: 'Test',
            galleryWidth: 800,
            galleryImageMargin: 20,
            galleryImageColumns: 2,
            galleryTargetFolder: 'homepage_gallery',
            imageQuality: 100
        }, options);

        var galleryImageWidth = settings.galleryWidth / settings.galleryImageColumns;
        var imageUrl = settings.server+settings.galleryTargetFolder;

        var otherMargin = Math.round(settings.galleryImageMargin / 2);
        var finalImageWidth = Math.round(galleryImageWidth - settings.galleryImageMargin);
        var finalImageHeight = Math.round(galleryImageWidth / 1.4);
        var finalGalleryWidth = settings.galleryWidth - settings.galleryImageMargin;

        $(this).before('<style>'+$(this).selector+' li:nth-child('+settings.galleryImageColumns+'n+1) { margin-left: 0; } '+$(this).selector+' li:first-child { margin-left: 0; } '+$(this).selector+' { width: '+finalGalleryWidth+'px; margin: 0px; } '+$(this).selector+' li { display: inline-block; list-style: none; margin-left: '+settings.galleryImageMargin+'px; margin-bottom: '+otherMargin+'px; } </style>');

        $.ajax({
            url: imageUrl,
            success: function(data){
                var extension = '.jpg';
                $(data).find("a:contains("+extension+")").each(function(){
                    // will loop through 
                    var filename = $(this).attr("href");
                    $('<li></li>').html('<a href="'+imageUrl+'/'+filename+'" class="fancybox"><img src="thumbnail.php?src='+imageUrl+'/'+filename+'&q='+settings.imageQuality+'&h='+finalImageHeight+'&w='+finalImageWidth+'"/></a>').appendTo(theObject);
                });
            }
        });

    };
}(jQuery));

这就是这样称呼的,并且完美地运作: HTML:<ul id="images"></ul>

jQuery的:

$('#images').createGallery({
    server: 'http://localhost/jQuery%20Gallery/images/galleries/',
    galleryName: 'Test',
    galleryWidth: 800,
    galleryImageMargin: 20,
    galleryImageColumns: 2,
    galleryTargetFolder: 'homepage_gallery',
    imageQuality: 100
});

现在,我想要做的是为新元素添加一个类,以便我可以在ie8中为它们添加一个类。我试过这个:

$(document).on('DOMNodeInserted', function(e) {
    $(e.target).addClass('triggerMargin');
});

我放在函数的底部,它在firefox和chrome等中运行良好,但它在ie8中完全被忽略。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

通过执行以下操作解决了这个问题 theObject.children('li:nth-child(2n+1)').addClass('triggerMargin');

其中theObject等于$(this),目标对象是为其子项添加一个类