使用javascript功能删除图像


Deleting images with javascript function

在一个页面中,我展示了一个文件夹中的图像的拇指,下面有一个链接"删除图像",通过此代码:

echo '<li> <a href="Gallery/'.$file.'" rel="lightbox['.$lightbox.']">';
echo '<div id="image" ><img src="Gallery/thumbs/'.$file.'" alt="" /><br>
<a href="javascript:Del();"><font style="font-size:9px">Delete Image</font>';
echo '</a></div></a></li>';

在删除图像上,我正在调用一个javascript函数Del()。我希望如果用户单击"删除图像",则应从其包含文件夹(即图库/缩略图)中删除图像缩略图。

函数 Del 是:

 <script type="text/javascript">
function Del(){
    var image_x = document.getElementById('image');
image_x.parentNode.removeChild(image_x);
}
</script>

此函数从页面中删除图像,而不是从文件夹中删除图像。而且它会删除它们,例如,如果我删除第三张图像,它将首先删除,然后是第二个,在连续的序列中。我希望删除图像,仅删除用户单击删除图像的图像

希望大家理解。

您可以使用,正如它在注释中所说的那样 AJAX 从服务器物理上删除文件。我建议您实现从服务器,数据库或文件中删除元素的通用功能 - 无论如何,因为通常您只需要调用一些URL,使用要删除的对象的传递 id,然后 - 转换 DOM 元素以显示对象已成功删除的方式。

function remove(el, url, callback) {
    $.post(url, {}, function(response) {
        // Expect that the response would be in JSON format (PHP - json_encode())
        response = $.parseJSON(response);
        // and in reponse JSON there should be the attibute called 'code', which is detects if the deleting where successfull,
        // if it's == 0 that's success, if not - error
        if (response.code == 0) {
            el.remove();
            if (typeof callback == 'function') {
                callback(response);
            } 
        }
    });
}

这是调用服务器端删除所需的函数。要使用它,请将此代码放在此代码中,您还应该在<a />上绑定单击事件上的触发器这将以这种方式开始删除:

$(document).on('click', 'a.delete', function(e) {
    // Do not allow browser go to the link's href
    e.preventDefault();
    // pass, as the first element div, which we need to delete from DOM,
    // as the second argument - URL from <a /> to server-side script
    // and third argument is th ecallback function which will remove() function call if the deleting where successfull
    remove($(this).parents('div:first'), $(this).attr('href'), function(r) {
        // here put the extra code to modify DOM after successfull delete
    });
});

<a />的属性href中,您应该放置指向服务器端脚本的链接,这将删除该文件。

希望有帮助。