[英]drop down menu will not work
I have a drop down menu that is supposed to work with four different menu choices, each given the same class. 我有一个下拉菜单,应该可以使用四个不同的菜单选项,每个选项都具有相同的类。 But my code is not working.
但是我的代码无法正常工作。 I want it to work with both chrome and IE.
我希望它能与chrome和IE一起使用。 The situation where it crashes is in my init method.
它崩溃的情况是在我的init方法中。 The console complains as following: Object # has no method 'getElementsByTagName'.
控制台抱怨如下:对象#没有方法'getElementsByTagName'。 Any solution ?
有什么办法吗?
function hideorShowField(list) {
var nodes = list.getElementsByTagName("li");
for (i = 1; i < nodes.length; i++) {
if (nodes[i].style.display == 'none') {
nodes[i].style.display = 'block';
}
else {
nodes[i].style.display = 'none';
}
}
}
function init() {
var list = document.getElementsByClassName("undermeny");
list1.getElementsByTagName("li")[0].onclick = function () {
hideorShowField(list);
};
}
window.onload = init;
My html code: 我的html代码:
<ul class="undermeny" >
<li>Opinion</li>
<li><a href="#">Ledare</a></li>
<li><a href="#">Aktuella frågor</a></li>
<li><a href="#">Per T Ohlsson</a></li>
<li><a href="#">Magda Forsberg</a></li>
</ul>
<ul class="undermeny" >
<li>Lokalt/Globalt</li>
<li><a href="#">Malmö</a></li>
<li><a href="#">Lund</a></li>
<li><a href="#">Limhamn</a></li>
<li><a href="#">Burlöv</a></li>
<li><a href="#">Eslöv</a></li>
<li><a href="#">Höör</a></li>
<li><a href="#">Kävlinge</a></li>
<li><a href="#">Lomma</a></li>
<li><a href="#">Svedala</a></li>
<li><a href="#">Staffanstorp</a></li>
<li><a href="#">Trelleborg</a></li>
<li><a href="#">Vellinge</a></li>
<li><a href="#">Sverige</a></li>
<li><a href="#">Öresund</a></li>
<li><a href="#">Världen</a></li>
<li><a href="#">Väder</a></li>
</ul>
<ul class="undermeny" >
<li>Ekonomi</li>
<li><a href="#">Nyheter</a></li>
<li><a href="#">Privata pengar</a></li>
<li><a href="#">Börs</a></li>
<li><a href="#">Fonder</a></li>
</ul>
<ul class="undermeny">
<li>Sport</li>
<li><a href="#">Fotboll</a></li>
<li><a href="#">Ishockey</a></li>
<li><a href="#">Handboll</a></li>
<li><a href="#">Fridrott</a></li>
</ul>
getElementsByClassName()
returns a nodeList
as well as getElementsByTagName()
. getElementsByClassName()
返回一个nodeList
以及getElementsByTagName()
。 So you probably need this: 因此,您可能需要这样做:
list[0].getElementsByTagName("li")[0].onclick = function () {...};
Or you've to iterate over the list
to attach eventhandlers to all 1st li
elements within ul
s with class undermeny
. 或者你遍历
list
到事件处理器附加到全部1st li
中的元素ul
与S类undermeny
。 That'll be something like this: 就像这样:
for (var n = 0; n < list.length; n++) {
list[n].getElementsByTagName("li")[0].onclick = function () {...};
}
list1
has not been initialized (although list
has). list1
尚未初始化(尽管list
已初始化)。 Fix the typo, and then you can iterate over the items in list
, calling getElementsByTagName()
on each. 修正拼写错误,然后可以遍历
list
的项目,对每个项目调用getElementsByTagName()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.