javascript - 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尝试使用单击事件,但当然这不会让用户真正做出选择。
解决方案
这可以通过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 中有效,但不保证在其他浏览器中有效。
推荐阅读
- php - 如何将 SQL“IN”循环查询从 1 简化为同一查询中的多个 IN 检查?
- apache-spark - PySpark - 对于每个 DF1 行应用随机 40% 的 DF2 行
- google-apps-script - Google Sheet:如何在 onChange 事件触发时获得实际更改?
- react-native - 从 React Native Drawer 中隐藏屏幕标签
- r - 循环遍历全局环境中的数据框并将功能应用于它们
- excel - 将形状移动限制在一个单元格内
- c - 无法识别的字符被添加到输出
- for-loop - GSheet 脚本:如何优化我的行和工作表迭代器
- pandas - 从 247sports 网站创建表格
- git - 使用相同的代码库维护多个版本