我習慣于D3.js將資料從我的 CSV 檔案匯入到專案檔案夾中,使用 Live Server 創建在 Visual Studio Code 中生成的 HTML 頁面。
這段代碼旨在定義texta 的div:
enter.append("div")
.text(d => d.attackmomentum)
.style("color", "White");
該CSV檔案(./ stackoverflow.csv)的格式如下:
id,attackmomentum
9832401,25
該值25正是文本值,如果它更改為例如 to 90,則文本將從 更改25為90。
考慮到這一點,在更新腳本中,我添加了.data(data,d=>d.attackmomentum):
let update_5 = select_5.selectAll(".matches")
.data(data,d=>d.id)
.data(data,d=>d.attackmomentum);
但是當attackmomentum根據我創建的觸發器每 5 秒更新一次我的 CSV 中的列值時,該值不會根據檔案中的內容而改變,它會保留我創建頁面時的值。
我應該更改什么才能更新此文本而無需重繪 整個頁面?
這是我的完整代碼(僅隱藏個人資料以便于查看)。
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.1.1/d3.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/d3-fetch@3"></script>
</head>
<body>
<div class="grid games" id="jogos-stackoverflow">
</div>
<script id="script-da-caixa-de-selecao-suspensa-5">
var select_5 = d3.select("#jogos-stackoverflow")
.append("div")
.attr("id","select-box-5")
.style("width","100%")
function valorparaiframe(iframevalue) {
let link = iframevalue;
return "https://........../" iframevalue "/";
}
async function update() {
let data = await d3.csv("./stackoverflow.csv");
let update_5 = select_5.selectAll(".matches")
.data(data,d=>d.id)
.data(data,d=>d.attackmomentum);
update_5.exit().remove();
// Enter new divs:
const enter = update_5.enter()
.append("div")
.attr("class","matches");
// Append the sum
enter.append("div")
.text(d => d.attackmomentum)
.style("color", "White");
// Append the children to entered divs:
enter.append("iframe")
.attr("src",d => valorparaiframe(d.id))
.style("width","100%")
.style("height","110");
}
update();
setInterval(update,5000);
</script>
</div>
</body>
</html>
uj5u.com熱心網友回復:
雙重.data讓我感到困惑,但這就是我要做的。
您只更新了新元素的文本(在.enter()僅選擇了新元素之后),而不是現有元素的文本。在我看來,使用.join而不是.enter更容易將一次性邏輯與更新邏輯分開。這給出了以下代碼:
async function update() {
let data = await d3.csv("./stackoverflow.csv");
select_5.selectAll(".matches")
.data(data, d => d.id)
.join(
enter => {
// First append the containing div
const divs = enter
.append("div")
.attr("class", "matches");
// Append a div with the text and the iframe
divs.append("div")
.style("color", "white");
divs.append("iframe")
.attr("src", d => valorparaiframe(d.id))
.style("width", "100%")
.style("height", "110")
// Return the divs matching ".matches" to be joined to the selection
return divs;
}
)
.select('div')
.text(d => d => d.attackmomentum);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/377326.html
標籤:javascript html 文件 d3.js
