Remove dynamically added
  • via onClick of
  • 2019-09-09 17:22发布

    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.

    标签: jquery tags
    3条回答
    家丑人穷心不美
    2楼-- · 2019-09-09 17:51

    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楼-- · 2019-09-09 18:09

    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

    查看更多
    我命由我不由天
    4楼-- · 2019-09-09 18:16

    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)

    查看更多
    登录 后发表回答