Jquery - Perform callback after append

后端 未结 4 1228
独厮守ぢ
独厮守ぢ 2020-12-15 03:25

I am appending content to a list using:

  $(\'a.ui-icon-cart\').click(function(){
         $(this).closest(\'li\').clone().appendTo(\'#cart ul\');
  });


        
相关标签:
4条回答
  • 2020-12-15 04:07

    jQuery's .each() takes a callback function and applies it to each element in the jQuery object.

    Imagine something like this:

    $('a.ui-icon-cart').click(function(){
      $(this).closest('li').clone().appendTo('#cart ul').each(function() {
        $(this).find('h5').remove(); 
        $(this).find('img').css({'height':'40px', 'width':'40px'});
        $(this).find('li').css({'height':'60px', 'width':'40px'});
      });
    });
    

    You could also just store the result and work on it instead:

    $('a.ui-icon-cart').click(function(){
      var $new = $(this).closest('li').clone().appendTo('#cart ul')
      $new.find('h5').remove(); 
      $new.find('img').css({'height':'40px', 'width':'40px'});
      $new.find('li').css({'height':'60px', 'width':'40px'});
    });
    

    I would also suggest that instead of mofiying the CSS like that you just add a class to your cloned li like this:

    $(this).closest('li').clone().addClass("new-item").appendTo('#cart ul');
    

    Then setup some styles like:

    .new-item img, .new-item li { height: 40px; width: 40px; }
    .new-item h5 { display: none }
    
    0 讨论(0)
  • 2020-12-15 04:13

    Unfortunatly adding callbacks to dom operations is not something that can be done in a neat fashion using javascript. For this reason it is not in the jQuery library. A settimeout with the timer "1ms" however always puts the function in the settimeout on the bottom of the call stack. This does work! The underscore.js library uses this technique in _.defer, which does exactly what you want.

    $('a.ui-icon-cart').click(function(){
        $(this).closest('li').clone().appendTo('#cart ul');
        setTimeout(function() {
            // The LI is now appended to #cart UL and you can mess around with it.
        }, 1);
    });
    
    0 讨论(0)
  • 2020-12-15 04:24

    You can just keep chaining further operations at the semicolon.

    $(this).closest('li').clone().appendTo('#cart ul').addClass('busy').fade('fast');
    

    etc

    0 讨论(0)
  • 2020-12-15 04:24

    In jquery you could use $() just after your appending contents code. This way you can be sure that the content is loaded and the DOM is ready before performing any tasks on the appended content.

    $(function(){
    //code that needs to be executed when DOM is ready, after manipulation
    });
    

    $() calls a function that either registers a DOM-ready callback (if a function is passed to it) or returns elements from the DOM (if a selector string or element is passed to it)

    You can find more here
    difference between $ and $() in jQuery
    http://api.jquery.com/ready/

    0 讨论(0)
提交回复
热议问题