Javascript 如何使用execCommand获取插入后的图像元素?

Javascript 如何使用execCommand获取插入后的图像元素?,javascript,html,contenteditable,execcommand,insert-image,Javascript,Html,Contenteditable,Execcommand,Insert Image,在我们使用execCommand插入图像后,是否有任何方法可以获取图像元素?比如说 e.execCommand('insertimage',0,'ronaldo.png') 您可以使用浏览器将插入符号放在插入的图像之后,然后再从插入的图像返回。以下要求DOM范围和选择支持,这排除了IE不使用insertimage,使用纯旧的insertHTML,并为要插入的元素提供ID,以便以后可以引用它。 i、 e 函数插入TML(img){ var id=“rand”+Math.random(); var

在我们使用execCommand插入图像后,是否有任何方法可以获取图像元素?比如说

e.execCommand('insertimage',0,'ronaldo.png')

您可以使用浏览器将插入符号放在插入的图像之后,然后再从插入的图像返回。以下要求DOM范围和选择支持,这排除了IE不使用
insertimage
,使用纯旧的
insertHTML
,并为要插入的元素提供ID,以便以后可以引用它。 i、 e

函数插入TML(img){
var id=“rand”+Math.random();
var doc=document.getElementById(“编辑器”);
doc=doc.document?doc.document:doc.contentWindow.document;
img=“”;
如果(全部文件){
var range=doc.selection.createRange();
range.pasteHTML(img);
范围。塌陷(假);
range.select();
}否则{
doc.execCommand(“insertHTML”,false,img);
}
返回单据getElementById(id);
};
这是我的方式:

e.execCommand('insertimage', 0, URI) // image's URI
image=$('img[src="'+URI+'"]').not('.handled').addClass('.handled');

//.not('.handled').addClass('.handled') is needed if there are many images with the same URI

回答得好,但有更简单的解决办法吗?@ABFORCE:我想不出来。
execCommand()
调用不会返回任何像引用插入的图像那样方便的结果,因此您必须进行一些DOM遍历。@ABFORCE:我认为内核James的答案更好。这是一个很好的建议,尽管我不想使用
文档。所有的
。但是,这在IE中行吗?execCommand的文档中说,insertHTML在IE中不起作用。这种技术的问题是,用户需要先选择一些文本,然后才能执行
insertHTML
。此解决方案容易受到攻击XSS@AlvaroMontoro,您能解释一下它是如何容易受到XSS攻击的吗?
function insertHTML(img) {
  var id = "rand" + Math.random();
  var doc = document.getElementById("editor");
  doc = doc.document ? doc.document : doc.contentWindow.document;
  img = "<img src='" + img + "' id=" + id + ">";

  if(document.all) {
    var range = doc.selection.createRange();
    range.pasteHTML(img);
    range.collapse(false);
    range.select();
  } else {
    doc.execCommand("insertHTML", false, img);
  }
  return doc.getElementById(id);
};
e.execCommand('insertimage', 0, URI) // image's URI
image=$('img[src="'+URI+'"]').not('.handled').addClass('.handled');

//.not('.handled').addClass('.handled') is needed if there are many images with the same URI