使用Javascript为Toast通知创建div区域(Create a div area for toast notifications by using Javascript)

编程入门 行业动态 更新时间:2024-10-27 08:24:20
使用Javascript为Toast通知创建div区域(Create a div area for toast notifications by using Javascript)

对于我的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 null

but 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(); } );

更多推荐

本文发布于:2023-08-01 13:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1359349.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:区域   通知   div   Javascript   Toast

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!