addEventListener to submenu links only, without jQuery
I would like to add an event listener to the #nav ul a
links only. Ordinerly i would use jQuery for this, but I can't with this project.
Basically I need to change the style of the sub men开发者_如何学Pythonu <UL>
when it’s child link <A>
has keyboard (tab) focus.
So, the HTML:
<ul id="nav">
<li><a href="#">Top 1</a></li>
<li><a href="#">Top 2</a>
<ul>
<li><a href="#">link</a></li>
<li><a href="#">link</a></li>
<li><a href="#">link</a></li>
</ul>
</li>
<li><a href="#">Top 3</a>
<ul>
<li><a href="#">link</a></li>
<li><a href="#">link</a></li>
<li><a href="#">link</a></li>
</ul>
</li>
</ul>
I've got this far with the Javascript but it's also selecting the top <ul id="nav">
element:
<script type="text/javascript">
function linkOn(e) {
var target = e.target.parentNode.parentNode;
target.style.color = "green";
}
function linkOff(e) {
var target = e.target.parentNode.parentNode;
target.style.color = "";
}
function addListeners() {
var arrayTop = document.getElementById("nav").getElementsByTagName("a");
for (var i = 0; i < arrayTop.length; i++)
{
arrayTop[i].addEventListener("focus",linkOn,false);
arrayTop[i].addEventListener("blur",linkOff,false);
}
}
window.addEventListener('load', addListeners, false);
</script>
You can limit iterate through the li's for #nav
and assign to their links... querySelectorALL would make things so much easier though.
Hard Method
http://jsfiddle.net/Btu4m/
var nodeList = document.getElementById("nav").getElementsByTagName("ul");
for (var x = 0; x < nodeList.length; x++)
{
var arrayTop = nodeList[x].getElementsByTagName("a");
for (var i = 0; i < arrayTop.length; i++)
{
arrayTop[i].addEventListener("focus",linkOn,false);
arrayTop[i].addEventListener("blur",linkOff,false);
}
}
querySelectorAll Method
http://jsfiddle.net/Btu4m/1/
var nodeList = document.querySelectorAll("#nav ul a");
for (var i = 0; i < nodeList.length; i++)
{
nodeList[i].addEventListener("focus",linkOn,false);
nodeList[i].addEventListener("blur",linkOff,false);
}
精彩评论