简体   繁体   中英

Selecting specific children on jQuery

I'm trying to hide the divs on click using .click() event and .hide() method.

The thing is each one has a different ID that was 'chosen' by the user, so i can't just write the code for each case.

Example:

HTML

<body>
      <div id="box">
           <div id="div1"></div>
           <div id="div2"></div>
           <div id="div3"></div>
      </div>
</body>

jQuery

$(document).ready(function() {
     $(---selector for all divs 1,2,3----).click(function) {
          $(----specificDivIClicked----).hide();
     });
});

Basicaly, i'm trying to find a way to delete only the div i click on.

Try to select all divs inside box div :

$(document).ready(function()
{
    $('#box div').click(function(){
        $(this).hide();
    });
});

 $(document).ready(function() { $('#box div').click(function(){ $(this).hide(); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="box"> <div id="div1">div1</div> <div id="div2">div2</div> <div id="div3">div3</div> </div> 

Thy blanks have been filled:

$(document).ready(function() {
     $('[id^="div"]').click(function() {
          //------------------------^---- You are missing (
          $(this).hide();
     });
});

Snippet

 $(document).ready(function() { $('[id^="div"]').click(function() { $(this).hide(); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="box"> <div id="div1">div1</div> <div id="div2">div2</div> <div id="div3">div3</div> </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