How to get the children of the $(this) selector?

前端 未结 18 2385
日久生厌
日久生厌 2020-11-22 05:10

I have a layout similar to this:

and would like to use a jQuery selector to selec

18条回答
  •  無奈伤痛
    2020-11-22 05:30

    You may have 0 to many tags inside of your

    .

    To find an element, use a .find().

    To keep your code safe, use a .each().

    Using .find() and .each() together prevents null reference errors in the case of 0 elements while also allowing for handling of multiple elements.

    // Set the click handler on your div
    $("body").off("click", "#mydiv").on("click", "#mydiv", function() {
    
      // Find the image using.find() and .each()
      $(this).find("img").each(function() {
      
            var img = this;  // "this" is, now, scoped to the image element
            
            // Do something with the image
            $(this).animate({
              width: ($(this).width() > 100 ? 100 : $(this).width() + 100) + "px"
            }, 500);
            
      });
      
    });
    #mydiv {
      text-align: center;
      vertical-align: middle;
      background-color: #000000;
      cursor: pointer;
      padding: 50px;
      
    }
    
    
    

提交回复
热议问题