如何选择一个项目,只需点击它在JavaScript中的组合框?
问题描述:
我的情况是我有一个梳子箱,我填写的项目是整数值动态通过javascript。如何选择一个项目,只需点击它在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对组合框项目
答
更改事件clikinng一次选择的项目。它会正常工作
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>
答
你接近。所有你需要做的是改变
var selectedItem = item.options[item.selectedIndex];
到
var selectedItem = item.value;
任何elemt您可以访问诸如ID和值的属性刚刚通过
<variable>.id
<variable>.value
,并作为外部点击,这是因为你在失去焦点后意味着它在Blur上。所以它会在你点击选择框后调用该函数。你可以做的是将其添加到.click函数。 JQuery会更好,因为你可以做一个onClick
事件来初始化你的select和一个onChange
事件来获得选定的项目
问题onclick是,当我点击组合打开它,看到项目它包含,第一个项目是立即通过点击组合框选择,然后我尝试选择项目 – struggling
您正在使用哪个浏览器?因为...我使用Chrome和我的片段在我的浏览器 –
我使用Firefox的工作很好.. – struggling