Javascript 添加另一个 div 而不是覆盖
Posted
技术标签:
【中文标题】Javascript 添加另一个 div 而不是覆盖【英文标题】:Javascript adds another div instead of overwriting 【发布时间】:2021-12-19 02:14:24 【问题描述】:我正在尝试使用以下脚本更改图表内容:
function switchType()
var e = document.getElementById("typeSelect");
var selected_value = e.options[e.selectedIndex].value;
console.log(selected_value)
anychart.onDocumentReady(function ()
var ents = entities_dict|safe
var dropdown = document.getElementById("typeSelect");
var val = dropdown.value;
/*
var data = [
value: 'GeopoliticalEntity',
children: [
% for i in entities_dict.get('GeopoliticalEntity') %
value: " i ",
% endfor %
]
];
*/
var data = [
];
data.push(value: val,
children: [
value: "country",
value: "europe",
value: "German",
])
//let result = data.map(a => a.children);
// create a chart and set the data
var chart = anychart.wordtree(data, "as-tree");
// set the chart title
chart.title("Word Tree: Data (Tree)");
// set the container id
chart.container("word_tree");
// initiate drawing the chart
chart.draw();
);
这是我的 html
<div class="container">
<div class="jumbotron">
% for k in survey %
<h2 class="display-4">Keyword Analysis</h2>
<h2 class="display-5">Most frequent keywords</h2>
<div id="word_cloud" style="width: 1000px; height: 500px; margin-bottom:5px;"></div><br>
<h2 class="display-5">Keyword frequency and their relevance score</h2>
<div id="bubble_chart" style="width: 1000px; height: 500px;"></div><br>
<h2 class="display-5">Entities found in responses</h2>
<select id="typeSelect" onchange="switchType()">
% for key in entities_dict.keys() %
% if loop.first %
<option selected="selected" value=" key "> key </option>
% else %
<option selected="selected" value=" key "> key </option>
% endif %
% endfor %
</select>
<div id="word_tree" style="width: 1000px; height: 500px;"></div>
% endfor %
</div>
</div>
结果是它创建图表,然后在下方创建另一个图表,并在每次选择更改时创建另一个图表。
有没有办法覆盖请求的 div 而不是在 HTML 页面上附加另一个?
【问题讨论】:
【参考方案1】:我在这个线程上找到的这段代码为我解决了这个问题:How to overwrite html element from javascript?
if (element)
// Get its parent
parent = element.parentNode;
// Create the new element
newElement = document.createElement('div');
// Set its ID and content
newElement.id = "word_tree";
// Insert the new one in front of the old one (this temporarily
// creates an invalid DOM tree [two elements with the same ID],
// but that's harmless because we're about to fix that).
parent.insertBefore(newElement, element);
// Remove the original
parent.removeChild(element);
【讨论】:
以上是关于Javascript 添加另一个 div 而不是覆盖的主要内容,如果未能解决你的问题,请参考以下文章
检查图像上的 alt-attribute 是不是具有价值并在 <div> 中添加另一个图像
当我将鼠标悬停在另一个 div 上时,如何使文本出现在一个 div 中?