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

…衆ロ難τιáo~ 提交于 2019-12-25 15:55:25

问题


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').html('<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.


回答1:


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)




回答2:


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
    })
})



回答3:


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



来源:https://stackoverflow.com/questions/5913761/remove-dynamically-added-li-via-onclick-of-img-contained-within

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!