2

This is my code. What I am trying to do is add a class "featured" to the first li item which gets added to this UL however, when I try this code, it does not work, it always add the class to every li inserted, while I want the class to be added only if there are no li in the ul and to the first li element added to this UL.

My code:

$(".img_add").click(function(event){
    event.preventDefault();
    $('input:submit, p.upload-result').hide(); // hide submit button + results while working
    $(this).parent().after('<p class="loading"><img src="<?php bloginfo('template_directory'); ?>/img/loading_2.gif" alt="" /></p>');
    var path_img = $("#img_url").val();
    var count_images_lib = $(".upload-images-lib").length;
    $.ajax({
        url: '<?php bloginfo('template_directory'); ?>/ajax/add_image_url.php',
        type: 'POST',
        data: { path : path_img },
        dataType: 'json',
        success: function(data){
            $('.loading').remove();
            $('input:submit').show();
            if (data.status) {
                $('.upload-images-lib').prepend(data.message);
                if (count_images_lib == 1) {
                    $('.upload-images-lib li:first-child').addClass('featured');
                }
                alert(count_images_lib);
                $('p.upload-result').fadeIn(500).html('<span class="success"><?php _e('Your image has been added successfully.','sofa'); ?></span>');
            } else {
                $('p.upload-result').fadeIn(500).html('<span class="error">' + data.message + '</span>');
            }
        }
    });
});

What I want is to add the class to the first loaded li only. Please note: data.message is actually a list item in html format.

The problem is with count_images_lib always returning 1 and thus my class is added everytime. It is not with first/last selector.

4

3 回答 3

2

你试过这个吗。。

$('.upload-images-lib li:first').addClass('featured');
于 2012-05-31T21:51:34.197 回答
0

您可能正在寻找 .first() 函数。

于 2012-05-31T21:52:02.657 回答
0

由于您正在执行前置操作,因此我假设加载的第一个项目将位于列表的底部。因此,使用:last选择器获取最后一项(第一次加载)并给它类。

$('.upload-images-lib li:last').addClass('featured')
于 2012-05-31T21:53:31.147 回答