使用下拉值引用JavaScript对象时出现问题



我正在处理一个表,该表将根据下拉菜单中选择的内容进行填充,但当进行选择时,输出显示为未定义。我正试图使用下拉值来引用函数中的对象。我想知道下拉列表中的值是否无法用于引用函数,或者是否需要以某种方式更改该值才能在脚本中正常工作。

我是Javascript的新手,提前感谢您的任何建议。下面是我正在使用的代码示例。

function fillrow() {
var selection = document.getElementById("description_dropdown").value;
const fordmotorco = {
sector: "Corporate Bonds",
cusip: "ABC5132",
coupon: "5%"
};
const abbvie = {
sector: "Corporate Bonds",
cusip: "A12345HJ",
coupon: "3%"
};
document.getElementById("col0").innerHTML = selection.sector;
document.getElementById("col1").innerHTML = selection.cusip;
document.getElementById("col2").innerHTML = selection.coupon;
}
<table id="holdings">
<thead>
<th>Sector</th>
<th>Cusip</th>
<th>Coupon</th>
</thead>
<tr id=select_security_row>
<td id="col0">-</td>
<td id="col1">-</td>
<td id="col2">-</td>
<td id="col3">
<select id="description_dropdown" type=text name=Cusip onchange="fillrow(this)">
<option value="fordmotorco">Ford Motor Co</option>
<option value="abbvie">Abbvie</option>
</select>
</td>
</tr>
</table>

进行选择时的值不会更改。更好的方法是将change事件侦听器附加到<select>。请参阅文档addEventListener,更改事件。因此,每次在下拉列表中选择一个选项时,都会调用addEventListener中传递的回调函数。

以下是对JS代码的建议更改:

function fillrow(value) {
const data = {
fordmotorco: {
sector: 'Corporate Bonds',
cusip: 'ABC5132',
coupon: '5%',
},
abbvie: { sector: 'Corporate Bonds', cusip: 'A12345HJ', coupon: '3%' },
}
document.getElementById('col0').innerHTML = data[value].sector
document.getElementById('col1').innerHTML = data[value].cusip
document.getElementById('col2').innerHTML = data[value].coupon
}
document
.getElementById('description_dropdown')
.addEventListener('change', function (event) {
fillrow(event.target.value)
})

附上了一个类似例子的工作演示。

这是我的解决方案:

let data = {
"fordmotorco": {
sector: "Corporate Bonds",
cusip: "ABC5132",
coupon: "5%"
},
"abbvie": {
sector: "Corporate Bonds",
cusip: "A12345HJ",
coupon: "3%"
}
};
function fillrow(selectBox) {
let selection = selectBox.value;
document.getElementById("col0").innerHTML = data[selection].sector;
document.getElementById("col1").innerHTML = data[selection].cusip;
document.getElementById("col2").innerHTML = data[selection].coupon;
}
<table id="holdings">
<thead>
<th>Sector</th>
<th>Cusip</th>
<th>Coupon</th>
</thead>
<tr id=select_security_row>
<td id="col0">-</td>
<td id="col1">-</td>
<td id="col2">-</td>
<td id="col3"><select id="description_dropdown" type=text name=Cusip onchange="fillrow(this)">
<option value="fordmotorco">Ford Motor Co</option>
<option value="abbvie">Abbvie</option>
</select></td>
</tr>
</table>

最新更新