I'm trying to create a custom drop down and using the code below it works pretty well - only one problem is if i have more than one drop down, all the links will only activate the first drop down. Any ideas on how I would fix that? (and yes I know about Suckerfish I just need to get this to work)
function toggle() {
var ele = document.getElementById("dropdown-items");
var text = document.getElementById("dropdown-menu");
if(ele.style.display == "block") {
ele.style.display = "none";
}
else {
ele.style.display = "block";
}
}
Html looks like:
<div id="mainSearch">
<div 开发者_如何学Goid="search-cat">
<div class="search-title">Destination</div>
<div id="cat-dropdown">
<a id="dropdown-menu" href="javascript:toggle();">Choose a Category...</a>
<div id="dropdown-items">
<ul>
<li id="dropdown-list"><a href="">Category One</a></li>
<li id="dropdown-list"><a href="">Category Two</a></li>
<li id="dropdown-list"><a href="">Category Three</a></li>
</ul>
</div>
</div>
</div>
<div id="search-cat">
<div class="search-title">Location</div>
<div id="cat-dropdown">
<a id="dropdown-menu" href="javascript:toggle();">Choose a Location...</a>
<div id="dropdown-items">
<ul>
<li id="dropdown-list"><a href="">Category One</a></li>
<li id="dropdown-list"><a href="">Category Two</a></li>
<li id="dropdown-list"><a href="">Category Three</a></li>
</ul>
</div>
</div>
</div>
</div>
Have your function take an ID, and pass in the element ID for the specific menu:
function toggle(menuId) {
var ele = document.getElementById(menuId);
if(ele.style.display == "block") {
ele.style.display = "none";
}
else {
ele.style.display = "block";
}
}
This way you can use a different ID for each menu and reference each one individually.
EDIT
You do not need much different javascript here. For each dropdown menu, you just need to change the href slightly:
<a id="dropdown-menu1" href="javascript:toggle('dropdown-menu1');">Choose a Category...</a>
<a id="dropdown-menu2" href="javascript:toggle('dropdown-menu2');">Choose a Category...</a>
Calling toggle
with the menu's id means the above modified toggle
function will toggle the exact menu you want.
I'm guessing it's because you're referencing the dropdown by ID and I'm guessing all your IDs are the same?
The HTML spec says the ID attribute of an element needs to be unique, this might be why you're having problems.
Please post a bit of HTML if you want a more concise answer :)
If you were to adapt your function so the element ID can be passed as a parameter this would solve your problem.
make the toggle function accept id as a parameter, you can then use toggle function for all items.
function toggle(var1) {
var ele = document.getElementById(var1);
You access your drop down by ID, and IDs are supposed to be unique within an HTML page. Without more information, my guess is that your problem is here.
精彩评论