简体   繁体   中英

How to completely remove div onclick with jquery?

There are some similar questions however my specific problem is an error in my code. I am able to remove the jumbotron div but there is a portion of it that still shows and I'm unsure why.

Here is the jsfiddle https://jsfiddle.net/dominiconorton/2bdxvrwq/2/

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Blank</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Blank <span class="sr-only">(current)</span></a>
            </li>
    </ul>
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Sign out</button>
  </div>
</nav>

<!-- Search tutorial -->
<div class="jumbotron" id="searchTutorial">
    <div class="container">
        <h1 class="display-4">Lorem Ipsum</h1>
        <p> Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit 
        </p>

    <div class="removeDiv">
    <p>
            <a class="btn btn-primary btn-lg " href="#" role="button">Close tutorial</a>
    </p>
    </div>

    </div>
</div>
// close jumbotron //
jQuery(function($) {
  $('.removeDiv').on('click', function() {
    $(this).parent('div').remove();
  });
});

I'm using Bootstrap 4.0 and JQuery 3.3.1

I tried changing the parent of the div so that the #searchTutorial is the parent and this didn't work as expected

I would like to completely remove the jumbotron div onclick of the close tutorial

Your javascript is removing the direct parent of the div being clicked, which is actually div.container . This isn't obvious because the indenting isn't consistent.

I would actually do @mark.hch's idea and use $(this).closest('.jumbotron').remove() .

If you can change the structure, you might consider using <section> instead of <div> for the major elements, so that you can use $(this).closest('section').remove();

您必须指定班级

jQuery(function($) {$('.removeDiv a').on('click', function() {$('.jumbotron').remove();});

removeDiv的父级是容器div,单击remove div即可按预期工作,它会删除其父级,而不是整个jumbotron div,这就是为什么在删除容器div后会出现灰色区域的原因,因此,您必须直接选择jumbotron 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