javascript - 如何通过在 javascript 的组合框中单击它来选择一个项目?

标签 javascript html combobox

我的情况是我有一个组合框,我通过 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/

相关文章:

javascript - casper.waitForSelector 不适用于动态 DOM 操作

php - 将 PHP 对象传递给 ajax PHP 脚本

javascript - 为什么我的点击事件处理程序(是 "is")正常工作?

javascript - 用元素和一致的间距填充固定宽度的网格

javascript - 谷歌+ API : Get users alternate email addresses

c# - 根据枚举名称动态查找枚举值

c# - 将数据绑定(bind)到组合框

javascript - 如何在 Web 应用程序中使用 Javascript 安全地访问 Windows Azure 移动服务?

javascript - fullCalendar - 禁用多选日

javascript - 是否可以通过输入组合框 jQuery 自动选择选项