简体   繁体   English

用纯JavaScript追加后如何获取html元素?

[英]How to get html element after append with pure JavaScript?

I found some JQuery solutions, but I am limited by school task restrictions to use pure Javascript, and I need to use specific early appended element that is still not in DOM for replacing by my CKEDITOR. 我找到了一些JQuery解决方案,但是由于学校任务的限制,我只能使用纯Javascript,而且我需要使用仍不在DOM中的特定早期附加元素替换为CKEDITOR。

Code: 码:

function newOption(){

     ...

     mainUL = document.getElementById("myUL");

     var inputA = document.createElement("input");
     inputA.type ="text";
     inputA.style = "margin-right: 45px";
     inputA.name = "option[]";
     inputA.id = inputID;

     mainUL.appendChild(inputA );

     CKEDITOR.replace(inputID).setData('Type anything you want ...');

     ...

}

By replacing my input with CKEDITOR will JS fail, because input, commonly, is still not in DOM. 通过用CKEDITOR替换我的输入,JS将失败,因为通常输入仍然不在DOM中。 I tried to use 我尝试使用

mainUL.innerHTML += "all elements like html text";

and this is working and will immediately insert elements into DOM, but I can't to use innerHTML, because it will remove old listeners (for example checked checkboxes that JS will set from checked to unchecked, what is my main problem due to I have to try using append DOM function). 并且可以正常工作,并且可以立即将元素插入DOM,但是我不能使用innerHTML,因为它会删除旧的侦听器(例如JS会将JS的选中复选框从选中状态设置为未选中状态,这是我的主要问题是尝试使用附加DOM函数)。

Try changing the code to wrap the call to CKEDITOR.replace in a setTimeout : 尝试更改代码以将对CKEDITOR.replace的调用包装在setTimeout

setTimeout(function() {
  CKEDITOR.replace(inputID).setData('Type anything you want ...');
},0).

This will allow the browser time to insert the element before trying to replace it. 这将使浏览器有时间在尝试替换元素之前插入该元素。

And I assume that inputID has a valid value in it... 我假设inputID有一个有效值...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM