我有一个表单将内容发布到墙上。我们可以在那里发布图片和文字。我将表单内容显示在contenteditable div中,所以邮箱显示人们想要上传的图像,并且他们也可以输入div。我注意到,虽然人们上传图像。它会像预期的那样被添加到div中,当它们开始输入时,它也会在文本周围添加照片容器。我怎样才能阻止这种情况发生?jquery添加多个div容器
这里是我的表单代码
<form id="post-form" action="Scripts/create-post.php" method="post" onsubmit="return setEditable();">
<input type="hidden" id="posted" name="posted" value=""/>
<div id="post-message" name="post-message" contentEditable="true"></div>
<input id="upload-pic" name="upload-pic" type="file"/>
<button class="post-buttons" onclick="chooseFile(); return false;">Add Photo</button>
<button class="post-buttons">Add Link</button>
<input type="submit" value="Post" />
<div class="cleared"></div>
</form>
这里是增加了上传照片到CONTENTEDITABLE DIV
function chooseFile() {
$("#upload-pic").click();
}
$(document).on('change', "#upload-pic", function(){
readURL(this);
});
function readURL(input){
if(input.files && input.files[0]){
var reader = new FileReader();
reader.onload = function(e){
$('#post-message').prepend("<div id='post-image-container'><img id='preview'/></div>");
$('#preview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
,你可以看到,当文件被上传它触发点击了jQuery将图像添加到div中,并将img包围在div id后置图像容器中。这是img添加到div后添加到文本的内容。
我知道这是因为警报的它显示我作为
<div id="post-image-container"><img src='whatever the path is'></div><div id="post-image-container">hello world(if this is what the user typed in)</div>
所以我设法找到了,如果文本是在CONTENTEDITABLE DIV已经或之前的div的价值,它不添加文本周围额外的div标签。只有在图像被插入后,你再次敲入回车键,我认为它会确认输入命中的图像发生了变化,然后是连续的键击。
我确信问题出在我的代码的document.on(change)部分。我相信当我输入它们是对文件的更改时,它正在想,并且再次插入语句,实现文本不是文件而只是离开div。但我不知道从哪里开始解决这个问题,或者如果那是真正的问题。 –
纠正我,如果我错了,只有当你选择文件上传,然后键入一些东西,然后选择一个不同的文件。你可以在prepend之前执行'$('#post-image-container')。remove();'去除先前的div。或者你可以检查'#post-image-container'是否已经存在,只需更新它而不是做一个新的前置。 –