我正在尝试为ImageUploader创建一个删除按钮。我选择图像并将其放在我页面的div元素中没有任何问题,这都是关于删除当前图像。
当我点击我的删除按钮时,它会给我所有的id和src,而不是我的删除按钮所选择的当前ID。看看我的删除按钮请在哪里我做控制台记录src和id。它给了我所有的id和src,我确实想要当前的id和src。
有人有解决方案吗?
这是完美的选择件。
frame.on( 'select', function() {
// Get media attachments details from the frame state
selections = frame.state().get('selection');
selections.map(function(attachment){
attachment = attachment.toJSON();
// Send the attachment URL to our custom image input field
imgContainer.append(
'<li>'
+ '<img data-attachment-id="id-media-1993'+attachment.id+'" src="'+attachment.url+'" class="gallery-thumbnail" alt="'+attachment.title+'" style="max-width:150px; max-height:150px;"/>'
+ '<a class="delete-custom-img" href="#">Remove Image</a>'
+ '</li>');
// Send the attachment id to our hidden input
imgIdInput.val(attachment.id);
console.log(attachment);
});
});
// Finally, open the modal on click
frame.open();
});
这是我的删除按钮
imgContainer.on( 'click', delImgLink, function(event){
event.preventDefault();
var galleryThumbnail = $('.gallery-thumbnail');
var galleryThumbnailID = $('.gallery-thumbnail').data('attachment-id');
var galleryThumbnailSrc = $('.gallery-thumbnail').attr('src');
$(galleryThumbnail).each(function(){
var imgSrc = $(this).attr('src');
console.log(imgSrc);
});
$(galleryThumbnail).each(function(){
var imgIDs = $(this).data("attachment-id");
console.log(imgIDs);
});
});
您可以从按钮中选择父元素,然后从中查找要查找的内容。
这样的事情
var img = $(this).closest('li').find('.gallery-thumbnail');
var galleryThumbnail = img;
var galleryThumbnailID = img.data('attachment-id');
var galleryThumbnailSrc = img.attr('src');
首先,我认为添加这样的事件处理程序会更加困惑:
$('.delete-custom-img').click(function() {...});
要么
$('.delete-custom-img', imgContainer).click(function() {...});
如果在imgContainer之外有这个类的其他元素,你不想添加事件处理程序。
但这是我个人的偏好,所以对你的问题:问题是你在页面上出现'.gallery-thumbnail',因为你没有指定任何jQuery的范围(如上面的imgContainer) 。所以当你点击它时你就在删除按钮的范围内。在生成的标记中,它与缩略图共享同一个父级,因此您可以执行以下操作:
var galleryThumbnail = $('.gallery-thumbnail', $(this).parent());
第二个参数指定jQuery搜索具有'.gallery-thumbnail'类的元素的范围。
没有测试过,但我很确定这可以解决你的问题。
干杯,莫