简体   繁体   English

有没有办法在 JavaScript 的动态数组中推送 html div?

[英]Is there a way to push an html div in a dynamic array in JavaScript?

I am trying to push a div in an array in JavaScript using template literals, let me give you an example.我正在尝试使用模板文字将 div 推JavaScript中的数组中,让我举个例子。

var myArray = [];

myArray.push(<div class="example">This is an example</div>); 

and then I can access the div in the array and display its content.然后我可以访问数组中的 div 并显示其内容。 But the statements after this line in my JavaScript acts weird.但是我的JavaScript中这一行之后的语句表现得很奇怪。 which make me wonder if I am doing the right thing.这让我想知道我是否在做正确的事情。 Is anything wrong with the way I am pushing my div into the array ?我将div推入array的方式有什么问题吗?

Add the single quote in the argument:在参数中添加单引号:

myArray.push('<div class="example">This is an example</div>');

you are missing quotes, you have to use it as a string:您缺少引号,您必须将其用作字符串:

var myArray = [];

myArray.push('<div class="example">This is an example</div>');

and then push it in some DOM element in order to show it然后将其推送到某个 DOM 元素中以显示它

myArray.push(`<div class="example">This is an example</div>`);

Can use ES6 template literals for inserting a variable or making it dynamic可以使用 ES6 模板文字来插入变量或使其动态化

    let array=[];
    let variable="This is a example";
    array.push(`<div>${variable}</div>`)

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

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