我想动态地将内容添加到可编辑的 div 中。
这个想法是:
<span class="">
<input type="file" class="input-file" id="input-file">file
</span>
<div contenteditable="true" class="div_edit" id="div_edit">
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
</div>
$(document).on("change", ".input-file", function(e){
upload_file();
});
function upload_file(){
var name = document.getElementById("input-file").files[0].name;
$.ajax({
url: "url",
method:"POST",
data: {"name": name},
beforeSend:function(){
console.log("upload...");
},
success:function(data){
var res = '<span class="span-added">' + data + '</span>';
const elInsert = document.querySelector("#input-file");
elInsert.addEventListener("click", () => {
document.execCommand("insertHTML", false, res);
});
}
});
return;
}
Document.execCommand()
方法已废弃,请使用 vanilla js 代替
例如:
function upload_file() {
// ...
success: function (data) {
var res = '<span class="span-added">' + data.name + '</span>';
const elInsert = document.querySelector("#input-file");
const doc = document.querySelector(".div_edit")
elInsert.addEventListener("click", () => {
doc.innerHTML += res; // use vanilla js instead of execCommand()
});
}
});
return;
}