Javascript error execCommand不是一个函数
我正在尝试使用type=“file”的输入元素上载图像,然后使用以下代码将图像附加到contenteditable字段集:Javascript error execCommand不是一个函数,javascript,Javascript,我正在尝试使用type=“file”的输入元素上载图像,然后使用以下代码将图像附加到contenteditable字段集: var doc = document; function file_upload() { var field = doc.getElementById("topic_details"), input = doc.body.appendChild(doc.createElement("input")); input.id = "blob"; input.setAt
var doc = document;
function file_upload() {
var field = doc.getElementById("topic_details"), input = doc.body.appendChild(doc.createElement("input"));
input.id = "blob";
input.setAttribute("type", "file");
input.click();
input.addEventListener("change", function() {
//reader.onload = function(e) { doc.getElementById("topic_details").innerHTML = "<img style='max-width: 320px; height: auto;' src='"+e.target.result+"' alt='' />"; }
reader.onload = function(e) {
field.execCommand("insertImage", false, e.target.result);
}
reader.readAsDataURL(doc.getElementById("blob").files[0]);
input.parentNode.removeChild(input);
}, false);
}
var doc=单据;
函数文件_upload(){
var field=doc.getElementById(“topic_details”),input=doc.body.appendChild(doc.createElement(“input”);
input.id=“blob”;
input.setAttribute(“类型”、“文件”);
输入。单击();
addEventListener(“change”,function()){
//reader.onload=函数(e){doc.getElementById(“主题_详细信息”).innerHTML=“”;}
reader.onload=函数(e){
field.execCommand(“insertImage”,false,e.target.result);
}
reader.readAsDataURL(doc.getElementById(“blob”).files[0]);
input.parentNode.removeChild(输入);
},假);
}
但我收到了这个错误:
未捕获类型错误:field.execCommand不是一个函数首先
execCommand()
是一个窗口
函数,只能在窗口
对象或其文档
上调用,因此调用field.execCommand()
是错误背后的代码:
未捕获类型错误:field.execCommand不是函数
您正在调用的另一个东西是doc.getElementById()
,而doc
未在file\u upload
函数中定义,请检查您是否在全局范围内声明了doc
,并且可以在file\u upload
函数中访问它
注意:
请注意,声明一个指向文档
对象的变量是无用的,因为通过文档
访问它总是很容易的,而且它是在窗口
范围中全局定义的。我找到了解决方案:
function file_upload() {
var field = doc.getElementById("topic_details"), input = doc.body.appendChild(doc.createElement("input"));
input.id = "blob";
input.setAttribute("type", "file");
input.click();
input.addEventListener("change", function() {
reader.onload = function(e) {
var range = doc.createRange();
range.selectNodeContents(field);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
doc.execCommand("insertImage", false, e.target.result);
}
reader.readAsDataURL(doc.getElementById("blob").files[0]);
input.parentNode.removeChild(input);
}, false);
}
谢谢大家的帮助。。cya在测试调用document.execCommand('copy')命令的函数时,我遇到了相同的错误 在测试document.execCommand时,什么帮助了我: 我在test.spec.ts文件的顶部添加了这行代码 document.execCommand=jest.fn()
在
doc.getElementById
中使用angular 9什么是doc
?我相信execCommand
只是文档
对象的一种方法。不是单个单据节点,我定义单据为var doc=document
位于documentRight顶部,但您正试图在字段
上运行execCommand
,这是一个单独的节点。好的,我将字段
替换为文档及其工作,但我看不到字段
中的图像,我将文档声明为var doc=document代码>在全局scope@Haithomy尝试在函数内部记录doc
,看看是否可以访问。我认为他定义doc
变量只是为了减少键入。@Barmar是的,键入额外的4个字符可能是一个难题。@chsdk我们要求提供一个最小的示例。这样就可以在所有使用中节省20个字符。但作业也有20个字符,因此是一个循环。:)