I have little piece of javascript to show/hide divs based on which link is clicked in a list. Its not very eligant, but it works fine. What I'd like to do is to assign an active state the a list item depending on which div is showing. Here is my JS and HTML:
var ids=new Array('section1','section2','section3','section4');
function switchid(id){
hideallids();
showdiv(id);
}
function hideallids(){
//loop through the array and hide each element by id
for (var i=0;i<ids.length;i++){
hidediv(ids[i]);
}
}
function hidediv(id) {
//safe function to hide an element with a specified id
开发者_如何学编程 document.getElementById(id).style.display = 'none';
}
function showdiv(id) {
//safe function to show an element with a specified id
document.getElementById(id).style.display = 'block';
}
html:
<ul>
<li class="activeItem"><a href="javascript:switchid('section1');">One</a></li>
<li><a href="javascript:switchid('section2');">Two</a></li>
<li><a href="javascript:switchid('section3');">Three</a></li>
<li><a href="javascript:switchid('section4');">Four</a></li>
</ul>
<div id="section1" style="display:block;">1111111</div>
<div id="section2" style="display:none;">2222222</div>
<div id="section3" style="display:none;">3333333</div>
<div id="section4" style="display:none;">4444444</div>
When section 2 (or whichever) is clicked, I'd like the class "activeItem" to be removed from the li it is currently on and applied to the current li. Is this possible with javascript? I think it is, but I can't figure out how to implement it client side.
Thanks!
If you're able to use jQuery (or something similar) as it has this ability built in: http://docs.jquery.com/Attributes - addClass/removeClass
Change your anchors to use the onclick event instead of the href javascript code.
<a onclick="switchid('section1');return false;">One</a>
Then pass the argument this
into your switchid
function. this
is a javascript keyword which in this scenario refers to the element (a
).
<a onclick="switchid('section1', this);return false;">One</a>
Now to make the switchid
function modify the list.
function switchid(id, el){
hideallids();
showdiv(id);
// rejiggered for text nodes
var li = el.parentNode.parentNode.childNodes[0];
while (li) {
if (!li.tagName || li.tagName.toLowerCase() != "li")
li = li.nextSibling; // skip the text node
if (li) {
li.className = "";
li = li.nextSibling;
}
}
el.parentNode.className = "activeItem";
}
Try it out: http://jsbin.com/esazu3/edit
精彩评论