如何使用javascript显示数据列表? [英] How to show datalist with javascript?
本文介绍了如何使用javascript显示数据列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嘿,我想在单击按钮时显示特定输入的数据列表,但找不到方法.
Hey I want to show datalist of specific input on click of button but I cannot find how to.
HTML
<input type="text" name="" value="" list="list" id='input'>
<datalist id='list'>
<option value="aaa">
<option value="bb">
</datalist>
<div onclick="showDataList(event,'input')">
Click
</div>
JS
function showDataList(e,id) {
document.getElementById(id).list.show()
}
我尝试过两次focus(),focus()和click(),并检查哪个事件数据列表show函数会触发但无济于事.
I have tried double focus(), focus() and click() and checking on which event datalist show function fires but to no avail.
推荐答案
要使用有效的下拉菜单,可以使用诸如material-ui/semantic-ui之类的第三方库更加简单.
但是,如果您想要干净的解决方案,则此默认方法可能会很有用.
To have working dropdown menu it's just simpler to use 3rd party libs such as material-ui/semantic-ui.
But if you want clean solution, this default approach might be useful.
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
.dropbtn {
background-color: #3498DB;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropbtn:hover, .dropbtn:focus {
background-color: #2980B9;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
overflow: auto;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {background-color: #ddd;}
.show {display: block;}
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<a href="#aaa">aaa</a>
<a href="#bb">bb</a>
</div>
</div>
这篇关于如何使用javascript显示数据列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文