Javascript 似乎无法正确读取某些 div 的类名,但并非全部
我的代码中有 15 个 div 标签。我不仅手动计算了代码,还使用 firebug 签入了 dom,并为每次迭代输出警报。
var toShow2 = document.getElementsByTagName("div");
for (var j=0;j<toShow2.length; j++) {
alert(toShow[j].className + " class iteration:" + j + "; checking for (show): " + show + "; checking for (hide): " + hide);
if (toShow[j].className.indexOf(show) > -1) {
var style = toShow[j].style;
style.display = "block";
}
if (toShow[j].className.indexOf(hide) > -1) {
var style = toShow[j].style;
style.display = "none";
}
}
警报显示类名(如果有)、当前迭代(0-14)、它正在查找的第一个参数for(显示)和它正在寻找的第二个参数(隐藏)。对于所有 15 个 div(不包括第一个),都有一个类名,但它只识别类名,甚至存在于以 0 开头的第 5 个和第 12 个位置)此代码位于函数内部,该函数可以传递 2 个变量:step1,步骤 2、步骤 3、步骤 4 或步骤 5。它识别第 5 个位置上的 step1 类名称和第 12 个位置上的 step2,否则
警报中的toShow[j].className
不会显示任何内容。
所有 div 的 dom 中出现的类名顺序如下。
- 类名]
- step1step2step3step4step5step2step3step4step5step1step2step3step4step5
- 类名称,它们
- 内容完全
- 已经
- 与我在警报中输出的搜索
- 检查
- 了
- [
- 无
- 我
- 的
- 我的
- html代码中
- 。
匹配 任何帮助将不胜感激。
I have 15 div tags in my code. Not only did I count in my code manually but I checked in the dom using firebug and output an alert for each iteration through
var toShow2 = document.getElementsByTagName("div");
for (var j=0;j<toShow2.length; j++) {
alert(toShow[j].className + " class iteration:" + j + "; checking for (show): " + show + "; checking for (hide): " + hide);
if (toShow[j].className.indexOf(show) > -1) {
var style = toShow[j].style;
style.display = "block";
}
if (toShow[j].className.indexOf(hide) > -1) {
var style = toShow[j].style;
style.display = "none";
}
}
The alert displays the className (if any), the current iteration(0-14), the first parameter it is looking for(show) and the 2nd parameter it is looking for(hide). For all 15 divs (excluding the first) there is a single class name but it only recognizes a class name even exist on the 5th and 12th position start with 0) This code is inside a function and the function can pass 2 variables: step1, step2, step3, step4, or step5. It recognizes the step1 class name on the 5th position and step2 on the 12th position otherwise the
toShow[j].className
in the alert comes up as nothing.
The order of class names that come up in the dom for all divs is this.
- [no class name]
- step1
- step2
- step3
- step4
- step5
- step2
- step3
- step4
- step5
- step1
- step2
- step3
- step4
- step5
I've checked the class names in my html code and they match up exactly with what I'm searching for as outputted in my alert. Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是您在循环中使用 toShow,但循环基于 toShow2。修复如下:
The problem is that you are using toShow in the loop, but the loop is based on toShow2. Fix it as follows:
乍一看,这是你想要的吗?没有测试过什么的。
show
和hide
未定义,因此您传递的是未定义的变量。At a quick glance, is this what you wanted? Haven't tested or anything.
show
andhide
aren't defined so you are passing in an undefined variable.