简体   繁体   English

JavaScript - 在不使用 display:none 的情况下显示一个 div

[英]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 ;我有一个 div,我想在点击时被“激活”,但只是第一次,只有当它还不存在时 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.我不想默认使用display:none ,因为之后返回页面时我必须再次单击才能显示它。

To sum up, is there any way to "activate" a div instead of using show/hide?综上所述,有没有办法“激活”一个 div 而不是使用显示/隐藏? ( createElement and append would make a new one on each click...) createElementappend会在每次点击时创建一个新元素......)

You can use appendTo() for that.您可以为此使用appendTo() If you give that div an unique ID, you can check if it exists如果你给那个div一个唯一的 ID,你可以检查它是否存在

 $('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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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