我的情况是我有一个组合框,我通过 javascript 动态填充整数值的项目。
问题是当我点击项目来选择它时,它仍然没有被选中,在点击那个项目之后,我需要再次点击组合框以外的地方来选择它。我不知道为什么?
我这样做的代码是(它在表内):
<body onload="loadView();">
<table>
<tr>
<td>
<select id="mydropdown" name="mydropdown" onblur="comboItemselect(this)"></select>
</td>
</tr>
</table>
</body>
我如何在组合中填充项目是这样的:
function loadView()
{
var sel = document.getElementById('mydropdown') // find the drop down
for (i = 1; i <= 50; i++) { // loop through all elements
var opt = document.createElement("option"); // Create the new element
opt.value = i; // set the value
opt.text = i; // set the text
sel.appendChild(opt); // add it to the select
}
}
/*When an item is selcted from CoboBox*/
function comboItemselect(item)
{
var selectedItem = item.options[item.selectedIndex];
alert("selected item is : " +selectedItem);
}
我之前在 wpf 或任何其他应用程序中所做的是,我只是单击要在组合框中选择的项目并且它被选中,但为什么我需要单击该项目一次然后再次单击组合框外部以选中它? 如何仅通过在该组合框项目上单击一次来选择项目
最佳答案
将事件从 onblur 更改为 onclick。它会很好地工作
function loadView() {
var sel = document.getElementById('mydropdown') // find the drop down
for (i = 1; i <= 50; i++) { // loop through all elements
var opt = document.createElement("option"); // Create the new element
opt.value = i; // set the value
opt.text = i; // set the text
sel.appendChild(opt); // add it to the select
}
}
/*When an item is selcted from CoboBox*/
function comboItemselect(item) {
var selectedItem = item.options[item.selectedIndex];
alert("selected item is : " + selectedItem.value);
}
<body onload="loadView();">
<table>
<tr>
<td>
<select id="mydropdown" name="mydropdown" onchange="comboItemselect(this)"></select>
</td>
</tr>
</table>
</body>
关于javascript - 如何通过在 javascript 的组合框中单击它来选择一个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33251361/