0

I'm fairly new to jQuery and really need help trying to figure this one out. I need a script that will:

  1. Add images from an image container to a different parent div container.
  2. Determine whether or not the image has been added to the div already
  3. Limit the amount of images that can be added to the new parent div
  4. Remove an image from the new parent div onclick
  5. Make the image available in its original container again for addition.

** If we could send the div image values (src or title) in a jquery $.post afterward that would be icing on the cake.

I seem to have 1,3 and 4 working. However 2 and 5 are driving me nuts. Maybe someone has this running somewhere??

Here's what I have already (in case it helps. i feel like i am way off.)

http://jsfiddle.net/pm284/LnqBt/

$(document).ready(function(){

    $('img.selectImage').click( function(e){
        e.preventDefault();

        var src = $(this).attr('src');
        var title = $(this).attr('title');
        var addimg = '<img class="added" src="' + src + '" title="' + title + '" height="50" width="50" />';    
        //first lets count the elements within the div.
        var number = $('#imgBox img').length;
        var imgMax = '5';
        if(number == imgMax){
            alert('You are at the max amout of images / 5');
        }//<!-end if tag

        //if the count is less than five we can add an image.   
        else {  
            $(this).css('border','1px solid #000');
            $('#addText').hide();   
            $('#imgBox').append(addimg);

            //we need to be able to remove the image also. 
            $('#imgBox img').click(function(e){
                e.preventDefault();
                $(this).remove();
            });

        }//<!-end else tag

    });
});
4

1 回答 1

1

只需添加条件检查单击图像的 src,您就可以查看是否已添加它。条件如下所示:

if(!$('#imgBox').find('[src="'+src+'"]').length)

然后,为了移除边框,我保存了单击的元素并在另一个单击函数中重用了它。最终代码如下所示:

if(!$('#imgBox').find('[src="'+src+'"]').length){
    var theImage = $(this);
    $(this).css('border','1px solid #000');
    $('#addText').hide();   
    $('#imgBox').append(addimg);

    //we need to be able to remove the image also. 
    $('#imgBox img').click(function(e){
        e.preventDefault();
        theImage.css('border', 'none')
        $(this).remove();
    });
}

小提琴:http: //jsfiddle.net/LnqBt/5/

于 2013-06-05T17:53:23.170 回答