对于我的Toast通知,我创建了一个名为“toastArea”的div容器。 所以当我在我的HTML文件中写
<div class="toastArea"></div>一切安好。 但是我想用JS动态创建它。 所以在我写的吐司控制器中
class ToastController { // class for toast notifications constructor() { this.CreateToastArea(); // create a div for every toasts } CreateToastArea() { var area = document.createElement("div"); // create div area.classList.add("toastArea"); // add a class to the div document.body.appendChild(area); // append div to the body } }但是当构造函数调用它所说的函数时
Cannot read property 'appendChild' of null但变量“area”不为空。 div正确创建。
我不明白那里有什么不对..
for my toast notifications I create a div container called "toastArea". So when I write in my HTML file
<div class="toastArea"></div>everything is fine. But I want to create it dynamically by using JS. So in my toast controller I write
class ToastController { // class for toast notifications constructor() { this.CreateToastArea(); // create a div for every toasts } CreateToastArea() { var area = document.createElement("div"); // create div area.classList.add("toastArea"); // add a class to the div document.body.appendChild(area); // append div to the body } }but when the constructor calls the function it says
Cannot read property 'appendChild' of nullbut the variable "area" is not null. The div got created correctly.
I don't get what's wrong there..
最满意答案
您的脚本已加载到标头中。 您需要将ToastController的实例化ToastController到ToastController的加载/解析。
例如,在jQuery中:
jQuery( document ).ready( function() { window.myToastController = new ToastController(); } );Your script is loaded in the header. You need to tie the instantiation of your ToastController to the loading/parsing of the body.
For example, in jQuery:
jQuery( document ).ready( function() { window.myToastController = new ToastController(); } );更多推荐
发布评论