gpt4 book ai didi

javascript - 运行函数后 DOM 不会刷新

转载 作者:行者123 更新时间:2023-11-28 15:12:15 25 4
gpt4 key购买 nike

我正在尝试制作一些带预览的上传图片功能,我将图片 URL 推送到数组并放置 if 条件以避免上传超过 1 张图片,并在删除图片预览时清空数组。
但是我有一些问题,当我选择一些图片让图片 A 并将其删除预览框时,它应该能够在下一步中选择图片 A,但它不能,除非我选择另一个具有不同名称的图片,下面是我的代码:

var arrCover = [];
var arrIm = [];

function uploadBanner(arr, prefix) {
var cover;
if(arr === 'coverBanner'){
cover = ($('.campaign-cover-image'))[0].files[0];
arr = arrCover;
}else {
cover = ($('.campaign-im-image'))[0].files[0];
arr = arrIm;
}

if (cover) {
var reader = new FileReader();
reader.onload = function (e) {
const image = e.target.result;
arr.push(image);
if(arr.length < 2){
var imgs = $(`
<div class="campaign-cover-image${prefix}">
<img class="image-cover${prefix}"
src=${arr.slice(-1)}>
</div>`);
var removeIcon = $(`<div class="delete-cover${prefix}">x</div>`);
$('.campaign-cover' + prefix).append(imgs);
$('.campaign-cover-image' + prefix).append(removeIcon);
} else {
alert('only 1 image');
}
};
reader.readAsDataURL(cover);
}

$(document.body).on('click','.delete-cover' + prefix, function(){
if(prefix === "-banner"){
var prevImg = $('.image-cover' + prefix).attr('src');
arrCover.filter(function(el){
var prevArr = el === prevImg;
if(prevArr){
arrCover = [];
$('.campaign-cover-image'+ prefix).val('');
}
});
$(this).closest('.campaign-cover-image' + prefix).remove();
}
});
}
$(document).ready(function(){
uploadBanner();
});
#upload_button {
display: inline-block;
}
#upload_button input[type=file] {
display:none;
}
.btn {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="campaign-cover-banner"></div>
<div id="upload_button">
<label>
<input
type="file"
class="campaign-cover-image"
onchange="uploadBanner('coverBanner','-banner');"
/><br>
<span class="btn btn-primary">Add image1</span>
</label>
</div>

<div class="campaign-cover-im"></div>
<div id="upload_button">
<label>
<input
type="file"
class="campaign-im-image"
onchange="uploadBanner('imBanner','-im');"
/><br>
<span class="btn btn-primary">Add image2</span>
</label>
</div>
</body>
</html>

最佳答案

这有点 hacky,但您可以尝试刷新您的 dom。

worker效果很好!

Force DOM refresh in JavaScript

关于javascript - 运行函数后 DOM 不会刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48865898/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com