亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

當動態創建該元素及其類名時,如何將 div 放入文檔中?

當動態創建該元素及其類名時,如何將 div 放入文檔中?

千巷貓影 2023-05-25 17:09:43
我有以下方法,主要目的是:能夠創建多個具有不同類的 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 并且出現以下錯誤:Uncaught TypeError: Cannot read property 'appendChild' of null我收到的先前答案是我需要將它放在文檔中,但是當我不知道類名是什么時,我將如何在文檔中放置一個新動態創建的 div 和一個新動態創建的類名是?
查看完整描述

1 回答

?
慕慕森

TA貢獻1856條經驗 獲得超17個贊

eParent需要DOM Element存在。例如,您可以調用document.querySelector('body')并獲取主體,然后它允許您附加到body元素。

不看結構很難直接給你解決方案HTML。但簡而言之,您要附加到的父元素需要在函數內部querySelector。


查看完整回答
反對 回復 2023-05-25
  • 1 回答
  • 0 關注
  • 129 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號