selected創建多個下拉選單時如何設定加載選項?
頁面加載完成后,第一個下拉選單應選擇“馬”,第二個下拉選單應選擇“牛”,第三個下拉選單應選擇“狐貍”。
let widgetContainer = d3.select('#dropdowns')
let animalNames = ["Horse", "Dog", "Cow", "Fox", "Cat", "Pig", "Aardvark", "Baboon", "Elephant"]
let selectedNames = ["Horse", "Cow", "Fox"]
let dropdowns = widgetContainer
.selectAll(".widget-select")
.data(selectedNames)
.join("select")
.attr("id", (d, idx) => `select-${idx}`)
.attr("class", "animal-select")
.on("change", (animalName, idx, selectElements) => {
let selectedValues = selectElements.map((elem) => elem.value);
// function that sets state for graph and renders
onAnimalSelect(selectedValues);
});
let options = dropdowns
.selectAll("option")
.data(animalNames)
.join("option")
.property("selected", (opt) => {
// how to find the parent node to set selected?
})
.attr("value", (opt) => opt)
.text((opt) => opt);
這是一個 JSFiddle:https ://jsfiddle.net/denisemauldin/x0znphky/3/
uj5u.com熱心網友回復:
結合使用第二個和第三個引數為我們提供了 DOM 元素(n[i]在此示例中),并且我們可以使用parentNode. 因此,它可以是:
.property("selected", (opt, i, n) => d3.select(n[i].parentNode).datum() === opt)
這是您進行更改的代碼:
顯示代碼片段
let widgetContainer = d3.select('#dropdowns')
let animalNames = ["Horse", "Dog", "Cow", "Fox", "Cat", "Pig", "Aardvark", "Baboon", "Elephant"]
let selectedNames = ["Horse", "Cow", "Fox"]
let dropdowns = widgetContainer
.selectAll(".widget-select")
.data(selectedNames)
.join("select")
.attr("id", (d, idx) => `select-${idx}`)
.attr("class", "animal-select")
.on("change", (animalName, idx, selectElements) => {
let selectedValues = selectElements.map((elem) => elem.value);
// function that sets state for graph and renders
onAnimalSelect(selectedValues);
});
let options = dropdowns
.selectAll("option")
.data(animalNames)
.join("option")
.property("selected", (opt, i, n) => d3.select(n[i].parentNode).datum() === opt)
.attr("value", (opt) => opt)
.text((opt) => opt);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.4.0/d3.min.js"></script>
<p>
Here are some dropdowns. How do we set the default value on load?
</p>
<div id="dropdowns">
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/494549.html
標籤:javascript d3.js
