我正在按照本指南创建 Search/Filter Dropdown 。
但是我有这个方法'Play()
',它返回一个名称数组(例如:
allNameMuseums()
我的JS代码:
array = ["Jack", "Paul", "George"]
我想用这些名称代替About,Base,Blog等...
答案 0 :(得分:1)
您可以遍历返回的数组,并将名称作为锚点附加到下拉列表中,如:
document.addEventListener("DOMContentLoaded", function(event) {
allNameMuseums().forEach(function(item){
document.getElementById("myDropdown").innerHTML += '<a href="'+item+'">'+item+'</a>';
})
});
注意::在执行代码之前,将代码放入DOMContentLoaded
事件监听器中,以确保所有DOM元素都已加载/
工作示例:
document.addEventListener("DOMContentLoaded", function(event) {
allNameMuseums().forEach(function(item) {
document.getElementById("myDropdown").innerHTML += '<a href="' + item + '">' + item + '</a>';
})
});
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
if (a[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
}
function allNameMuseums() {
return ["Jack", "Paul", "George"];
}
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropbtn:hover,
.dropbtn:focus {
background-color: #3e8e41;
}
#myInput {
border-box: box-sizing;
background-image: url('searchicon.png');
background-position: 14px 12px;
background-repeat: no-repeat;
font-size: 16px;
padding: 14px 20px 12px 45px;
border: none;
border-bottom: 1px solid #ddd;
}
#myInput:focus {
outline: 3px solid #ddd;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f6f6f6;
min-width: 230px;
overflow: auto;
border: 1px solid #ddd;
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;
}
<h2>Search/Filter Dropdown</h2>
<p>Click on the button to open the dropdown menu, and use the input field to search for a specific dropdown link.</p>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
</div>
</div>