gpt4 book ai didi

java - 根据在另一个组合框中选择的内容,使用 Map 中的值动态填充组合框

转载 作者:行者123 更新时间:2023-11-29 06:48:12 25 4
gpt4 key购买 nike

好的,这是给 Java/JavaScript 专家的:

在我的应用程序中,其中一个 Controller 将 TreeMap 传递给它的 JSP。该 map 以汽车制造商的名称作为键,以汽车对象列表作为值。这些 Car 对象是包含汽车名称、ID、生产年份等的简单 bean。所以, map 看起来像这样(这只是一个例子,为了澄清一点):

key :保时捷
值:包含三个 Car 对象的列表(例如 911、Carrera、Boxter 以及它们的生产年份和 ID)
关键:菲亚特
值:包含两个 Car 对象的列表(例如,Punto 和 Uno)
等等……

现在,在我的 JSP 中我有两个组合框。一个应该收到一份汽车制造商列表( map 上的键 - 这部分我知道怎么做),另一个应该动态更改以在用户选择特定时显示汽车名称来自第一个组合框的制造商。因此,例如,用户在第一个组合框中选择“Porsche”,第二个组合框立即显示“911、Carrera、Boxter”...

在花了几天时间尝试找出如何做到这一点之后,我准备承认失败。我尝试了很多不同的东西,但每次我都会在某个地方碰壁。有人可以建议我应该如何处理这个问题吗?是的,我是一个 JavaScript 新手,如果有人想知道......

编辑:我已将其重新标记为代码挑战。感谢任何在不使用任何 JavaScript 框架(如 JQuery)的情况下解决此问题的人。

最佳答案

我就是喜欢挑战。

没有 jQuery,只有普通的 javascript,在 Safari 上测试过。

我想提前添加以下备注:

  • 由于错误而失败了很长时间检查。
  • 生成了两个部分;带有 map 的第一个脚本节点和制造商的内容选择
  • 在我的机器上工作 (TM)( Safari /OS X)
  • 没有(css)样式应用。我品味不好所以反正也没用。

.

<body>
<script>
// DYNAMIC
// Generate in JSP
// You can put the script tag in the body
var modelsPerManufacturer = {
'porsche' : [ 'boxter', '911', 'carrera' ],
'fiat': [ 'punto', 'uno' ]
};
</script>

<script>
// STATIC
function setSelectOptionsForModels(modelArray) {
var selectBox = document.myForm.models;

for (i = selectBox.length - 1; i>= 0; i--) {
// Bottom-up for less flicker
selectBox.remove(i);
}

for (i = 0; i< modelArray.length; i++) {
var text = modelArray[i];
var opt = new Option(text,text, false, false);
selectBox.add(opt);
}
}

function setModels() {
var index = document.myForm.manufacturer.selectedIndex;
if (index == -1) {
return;
}

var manufacturerOption = document.myForm.manufacturer.options[index];
if (!manufacturerOption) {
// Strange, the form does not have an option with given index.
return;
}
manufacturer = manufacturerOption.value;

var modelsForManufacturer = modelsPerManufacturer[manufacturer];
if (!modelsForManufacturer) {
// This modelsForManufacturer is not in the modelsPerManufacturer map
return; // or alert
}
setSelectOptionsForModels(modelsForManufacturer);
}

function modelSelected() {
var index = document.myForm.models.selectedIndex;
if (index == -1) {
return;
}
alert("You selected " + document.myForm.models.options[index].value);
}
</script>
<form name="myForm">
<select onchange="setModels()" id="manufacturer" size="5">
<!-- Options generated by the JSP -->
<!-- value is index of the modelsPerManufacturer map -->
<option value="porsche">Porsche</option>
<option value="fiat">Fiat</option>
</select>

<select onChange="modelSelected()" id="models" size="5">
<!-- Filled dynamically by setModels -->
</select>
</form>

</body>

关于java - 根据在另一个组合框中选择的内容,使用 Map 中的值动态填充组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/156852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com