What I think is happening is that your click handler is being called on the first click, but your if
test isn't working the way you expect.
(我认为正在发生的事情是,你的点击处理程序被调用的第一次点击,但是你if
测试不工作,你期望的方式。)
This line: (这行:)
if(node_list[i].style.display == 'none')
...is testing whether the element has an inline style set.
(...正在测试元素是否具有内联样式集。)
Which it doesn't: it's hidden via a CSS rule that applies to all such inputs. (并非如此:它通过适用于所有此类输入的CSS规则隐藏。)
So then your else
case executes and the .display
is set to 'none'
. (因此,您的else
案例将执行,并且.display
设置为'none'
。)
Then on the next click, the if
works as expected and changes .display
to 'block'
. (然后, 在下一次单击时, if
将按预期工作,并将.display
更改为'block'
。)
You can see this for yourself if you actually debug your function a little to see if it is getting called and test the value of that .display
property - as you can see here: http://jsfiddle.net/uLjxp3ha/ (note: I don't recommend alert()
s for debugging).
(如果您实际调试一下函数以查看它是否被调用并测试该.display
属性的值, .display
可以自己查看一下-如您在此处看到的: http : //jsfiddle.net/uLjxp3ha/ (注意:我不建议使用alert()
进行调试)。)
Checking the current visibility as set by stylesheet rules is a bit trickier because it doesn't work consistently across browsers.
(检查由样式表规则设置的当前可见性有些棘手,因为它在浏览器之间无法始终如一地工作。)
You may need to test for existence of .currentStyle
and .getComputedStyle()
to allow for whichever one the current browser might support. (您可能需要测试.currentStyle
和.getComputedStyle()
存在,以允许当前浏览器可能支持的任何一种。)
Have a look at this answer to another question for more information about that. (请查看另一个问题的答案,以获取有关此问题的更多信息。)
But in your case given that you know the checkboxes are hidden to begin with you can simply invert your if/else:
(但是在您的情况下,您知道复选框已隐藏,因此您可以简单地将if / else反转:)
if(node_list[i].style.display == 'block') {
node_list[i].style.display = 'none';
} else {
node_list[i].style.display = 'block';
}
The .display
will not be 'block'
to start with, so the else will be executed and the elements will be displayed.
(.display
不会以'block'
开头,因此将执行else并显示元素。)
Demo: http://jsfiddle.net/uLjxp3ha/1/
(演示: http : //jsfiddle.net/uLjxp3ha/1/)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…