开发者

Remove dynamically added <li> via onClick of <img> contained within

开发者 https://www.devze.com 2023-03-03 17:04 出处:网络
I\'m using the script from http://webdeveloperplus.com/jquery/ajax-multiple-file-upload-form-using-jquery/

I'm using the script from http://webdeveloperplus.com/jquery/ajax-multiple-file-upload-form-using-jquery/ I modified the onComplete to add a link to remove the image. In the remove_me() function, I want to: 1. remove the <li> for the file clicked 2. call a PHP script on the server via ajax to delete the file from the server due to it being uploaded already.

if(response==="success"){
  $('<li></li>').appendTo('#files').htm开发者_如何学Cl('<img src="./uploads/'+file+'" alt="" /><br />'+file+'<br />Click to Remove<img src="cross.png" onclick="remove_me(\'./uploads/'+file+'\')" />').addClass('success');
} else{
  $('<li></li>').appendTo('#files').text(file).addClass('error');
}

In the remove_me() function, I am able to get the image name easily because I'm passing it via the onClick but I am not sure how I can remove the <li> that contains the image. The filename will be passed to the PHP function via an ajax call. I know how to do that, it's just removing the <li> that I'm having trouble with.


I am not sure with what you are showing here why it is not working since i can not see the remove_me() function but I will show you how to do it the way i would do it.

you could use $(this) in the remove_me() function like so:

$(this).closest('li').remove();

This would start where clicked and go to the closest li tag and remove it.

(darnit two people just answered ... im not going to look ... got to learn to type faster lol)


If you are using jQuery, you shouldn't use inline event binding like 'onClick'. You yould use the standard way of binding events, that is:

$(function() {
    $('img').click(function() {
        // process here
    })
})

So, you can access there to any related DOM element. In your case, you can get the parent <li> as $(this).parent() and remove it with $(this).parent().remove();

ADDED: If you are adding those elements dinamically, you must bind the events using live, like:

$(function() {
    $('img').live('click', function() {
        // process here
    })
})


If the image is the only element inside the LI tag, then you can use the DOM to delete the parentNode of the image, thereby delete the LI.

https://developer.mozilla.org/En/DOM/Node.parentNode http://reference.sitepoint.com/javascript/Node/parentNode

0

精彩评论

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

关注公众号