简体   繁体   中英

JavaScript onClick work only after second click

I found another similar questios, but almost all is for advanced things, like Android development. My question is simple, I think. I have this two codes:

function toggle(d)
{
    var o=document.getElementById(d);
    o.style.display=(o.style.display=='none')?'block':'none';
}

And in another file, I got that:

<a href="javascript:;" onmouseover="toggle('maisinfo');">More Info </a>

When I click on got the mouseover (second code), it just work after second try.

Anyone know where is the problem?

Obs.: The first code is in the header.php and the second on single.php (WORDPRESS)

The first time, d is set by CSS; JavaScript doesn't see that style property (See Get the Rendered Style ). It initially sees o.style.display === "" (which is not 'none'). Consequently, the first click sets it to none and the second sets it to block.

Change it to:

o.style.display = (o.style.display === 'block') ? 'none':'block';

因为第一次没有设置显示属性因此它不等于“无”

Well, there's nothing wrong with your code above. Maybe something's up with your style declaration, like setting it to block in the start which you might not want. Here's a simple JSFiddle I made for testing your code: http://jsfiddle.net/77DMd/1/

Hope this helps.

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