【发布时间】:2021-11-22 23:19:05
【问题描述】:
我希望创建以下内容:
- 当用户单击按钮时,会创建一个新的下拉菜单。
- 当用户从此下拉列表中选择一个选项时,会根据所选值创建/更新第二个下拉列表。
用例:
Project 允许用户指定要使用的算法。使用各种算法,我希望能够允许用户选择参数。所以用户按下按钮来显示他们想要选择一个新参数。一个下拉列表显示所有可能的参数,然后当他们选择一个时,第二个下拉列表显示该选定参数的所有可能值。
我需要他们能够添加任意数量的这些参数/值对。 我也想知道之后如何正确访问每个数据对。
我有它的骨架(我认为)但不完全。任何帮助将不胜感激。
这是我迄今为止所拥有的。 ( 见:JSFiddle)
HTML
<div id="banner-message">
<div>
<button id="selectParam">New Parameter</button>
</div>
<div class="row">
<div id="newParamName"></div>
<div id="newParamValue"></div>
</div>
</div>
JS
document.getElementById('selectParam').onclick = function () {
// Get the parameters for the chosen algorithm
params = getParameters("Algo_A")
// get the names of the parameters
var name = Object.keys(params);
// Create a new Select Element and set the name and ID value
var param = document.createElement("select");
param.name = "paramName";
param.id = "paramName";
// Add each parameter as a option for the selection
for (const val of name) {
var option = document.createElement("option");
option.value = val;
option.text = val;
param.appendChild(option);
}
// Add the new selection dropdown to the
document.getElementById("newParamName").appendChild(param)
}
// When the user clicks on the created selection dropdown
document.getElementById('newParamName').onclick = function () {
// Get the parameters for the chosen algorithm
params = getParameters("Algo_A")
// Determines what parameter was chosen from the dropdown
var param = document.getElementById('paramName').value
// Determines the possible values for that parameter
var values = params[param]
// Creates a new selection dropdown with these new values as possible options
var paramValue = document.createElement("select");
paramValue.name = "paramValue";
paramValue.id = "paramValue";
for (const val of values) {
var option1 = document.createElement("option");
option1.value = val;
option1.text = val;
paramValue.appendChild(option1);
}
// Appends the dropdown to the page
document.getElementById("newParamValue").appendChild(paramValue)
}
function getParameters(projType) {
params = {}
if (projType == 'Algo_A') {
params.param_a = ['a1', 'a2', 'a3', 'a4']
params.param_b = ['b1', 'b2', 'b3', 'b4']
params.param_c = ['c1', 'c2', 'c3', 'c4']
params.param_d = ['d1', 'd2', 'd3', 'd4']
}
return params
}
【问题讨论】:
标签: javascript dynamic dropdown