【发布时间】:2018-07-12 08:49:17
【问题描述】:
我在克隆 div 中有这段代码。现在到克隆,没问题。现在这个克隆的 div 中有 img 标签,如果我点击添加新的,它会在上传时设置图像 src,然后它会克隆 div 以及带有预览的图像,因为我在里面有 img 标签,我想要在 div 内部或外部相同的东西但在同一个位置。有什么想法吗?另外,当我在克隆新 div 后上传图片时,还有一件事是错误的,你会看到所有的工作只是运行 sn-p。
这是我的代码
$(".file-input-area").click(function() {
$("#file-upload").click();
});
$('#copy-button').click(function() {
var target = $('.clone-element:last');
target.clone(true, true).insertAfter(target);
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#uploaded-image').attr('src', e.target.result).css({
'width': '100%',
'height': '120px'
});
}
reader.readAsDataURL(input.files[0]);
}
}
$("#file-upload").change(function() {
$(".file-input-area").hide();
$(".uploaded-image-div").show();
readURL(this);
});
.file-input-area {
background: #e9e8e8;
padding: 20px 0px 0px 0px;
cursor: pointer;
border: #263238 dashed 1px;
border-radius: 3px;
text-align: center;
height: 92px;
color: #e6294b;
font-size: 14px;
line-height: 10px;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row clone-element">
<div class="col-md-6">
<div class="form-group">
<label>Upload Image</label>
<input type="file" id="file-upload" style="display:none !important;" />
<div class="file-input-area">
<h3> <i class="fa fa-plus"></i> Upload File </h3>
<span class="input-project1"> choose</span> to choose file.
</div>
</div>
<div class="uploaded-image-div" style="display:none;">
<img src="#" id="uploaded-image" alt="uploaded-image">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Description</label>
<textarea rows="4" cols="5" class="form-control" placeholder="Enter your message here"></textarea>
</div>
</div>
</div>
<input type="button" class="btn btn-primary" id="copy-button" title="add new image and desciption" value="New image + Desc">
【问题讨论】:
-
在原始“上传文件”视图中简单运行代码、创建克隆和上传图像会发生什么?它是否也应该出现在克隆“上传文件”视图中?还是什么都不做?
-
上传文件应该显示而不是里面的图像。图片仅在点击上传 div 时显示。单击添加按钮时图像重复我不希望图像仅克隆 div 。任何解决方案
-
这个问题的发生是因为元素的 id 相同。在这种情况下,您应该使用父、子和兄弟关系来查找元素,而不是在 jquery 中使用 id。
标签: javascript jquery html css