问题描述
我的主要意图是采用以下方法:
- 能够创建多个具有不同类的div
- 使用这些,然后我们为多个图表创建“容器”
问题在于此方法动态创建了div和类。我需要在文档中提供它们以实际使用appendChild,但是由于它们是动态创建的,因此我无法将其硬编码到文档中
我已在必要之处发表了评论,以表明这些行的用途。
createChartContainer(chartRef) {
// bring up the grid object
for (var chartDataInTable of this.tableData) {
// if this grid does not have 0 charts
if(chartDataInTable.summary_charts.length != 0) {
// create div
var createDiv = document.createElement('div');
// generate a string I can use as the class name for the newly created div shown above
var randomStringAsClassNames = Math.random().toString(36).substring(7);
// assign the random string as the className for the newly created div
createDiv.className = 'div_' + randomStringAsClassNames;
// chartClassName is defined as a string in data: () => ....
this.chartClassName = createDiv.className;
// non-negotiable as this shows the details of the created chart
var eChart = chartRef.chartElement;
// select the div that we've just created
var eParent = document.querySelector("." + this.chartClassName + "");
eParent.appendChild(eChart);
}
}
},STRUCTURE OF ELEMENTS IN <script> TAG i.e. the Document (Note: I'm using Vue JS) (e.g. where the div should go)
<template>
<v-card>
<v-text-field
label="Please enter chart name"
v-model="chartName"
append-outer-icon="mdi-content-save"
@click:append-outer="saveChart"
/>
</v-card>
<template>
console.log(eParent)返回null,并且出现以下错误:未捕获的TypeError:无法读取null的属性'appendChild'
我收到的上一个答案是我需要将其放入文档中,但是当我不知道什么内容时,如何在文档中放入具有动态创建类名的新动态创建的div呢?班级的名字是?
解决方法
eParent
必须是存在的DOM Element
。例如,您可以调用document.querySelector('body')
并获取正文,然后将其附加到body
元素上。
在没有看到HTML
结构的情况下很难为您提供直接的解决方案。但是,简而言之,要附加到的父元素必须位于querySelector
函数内部。