简体   繁体   中英

JavaScript - Show a div without using display:none

I have a div that I want to be "activated" on a click but only the first time, only when it doesn't exist yet ; I don't want to use display:none by default because when coming back to the page afterwards I would have to click again to make it appear.

To sum up, is there any way to "activate" a div instead of using show/hide? ( createElement and append would make a new one on each click...)

You can use appendTo() for that. If you give that div an unique ID, you can check if it exists

 $('button').on('click', function() { if( $('#uniqueID').length == 0 ) { $('<div id="uniqueID">This is a div</div>').appendTo('body'); } });
 div { border: 1px solid blue; margin: 1em; padding: 1em; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button>Add div</button>

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