首页 > 解决方案 > JavaScript 在下拉列表时清除选择列表

问题描述

有没有办法在下拉 HTML 选择列表时触发事件?我不是在问它什么时候关闭,而是在你第一次放下它的时候。

当用户单击下拉菜单的向下箭头时,我想设置 selectedIndex = -1。

大多数网站都以空白条目或“选择...”之类的虚拟条目开始下拉菜单。我只想拥有这些值本身,并在他们点击时让列表自行清除。

这是我开始的,但是在他们做出选择后它会触发,这不是我想要的——我想要列表下降时。

<select id="ddlMylist">
  <option value="10">Choice 1</option>
  <option value="20">Choice 2</option>
  <option value="30">Choice 3</option>
  <option value="40">Choice 4</option>
</select>


document.getElementById("ddlMylist").onclick = function(){
  //this clears the list when they click, but it fires when they
  //are making an actual choice, which isn't what I want
  document.getElementById("ddlMylist").selectedIndex=-1;
  }

这个 JSFiddle尝试使用单击事件,但当然这不会让用户真正做出选择。

标签: javascript

解决方案


这可以通过mousedown事件来实现,该事件在用户首次单击<select>元素时触发:

// mousedown is fired when mouse click is first pressed down on
// the <select> element 
document
.getElementById("ddlMylist")
.addEventListener("mousedown", function(){ 
  
  // Resets selected option item
  document.getElementById("ddlMylist").selectedIndex = -1;
})
<select id="ddlMylist">
  <option value="10">Choice 1</option>
  <option value="20">Choice 2</option>
  <option value="30">Choice 3</option>
  <option value="40">Choice 4</option>
</select>

请记住,此方法已经过测试并在 Chrome 中有效,但不保证在其他浏览器中有效


推荐阅读