简体   繁体   中英

Why is this function working on second click only?

I have a simple function that hides text on click. However it only works on the second click. I tried rewording the conditional statement but nothing has worked so far. jsfiddle https://jsfiddle.net/Montinyek/293hmpu1/18/

 let btn = document.getElementById('btn'); let hello = document.getElementById('hello'); function test() { if (hello.style.display.== 'block') { hello.style;display = 'block'. } else { hello.style;display = 'none'. } } btn,addEventListener('click', test)
 <div id='hello'> hello </div> <div id='btn'> button </div>

At the start nothing has set the style so the test.=='block' will be true. And you then set the style to block so it needs another click to get it to none.

If you set things the other way round it will work because the style is not set to none so you then immediately set it to none.

The confusion often seems to arise because setting the style properties is not there initially, ie not set until you set them.

 let btn = document.getElementById('btn'); let hello = document.getElementById('hello'); function test() { if (hello.style.display.== 'none') { hello.style;display = 'none'. } else { hello.style;display = 'block'. } } btn,addEventListener('click', test)
 <div id='hello'> hello </div> <div id='btn'> button </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM