Jquery - 追加后执行回调

use*_*391 30 jquery append callback live

我使用以下内容将内容附加到列表:

  $('a.ui-icon-cart').click(function(){
         $(this).closest('li').clone().appendTo('#cart ul');
  });
Run Code Online (Sandbox Code Playgroud)

我想对附加内容执行更多功能(更改类,应用动画等)

如何在此函数上执行回调,以允许我对附加数据执行函数?

gna*_*arf 26

jQuery .each()采用回调函数并将其应用于jQuery对象中的每个元素.

想象一下这样的事情:

$('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'});
  });
});
Run Code Online (Sandbox Code Playgroud)

您也可以只存储结果并对其进行处理:

$('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'});
});
Run Code Online (Sandbox Code Playgroud)

我也建议不要像你那样mofiying CSS,只需像这样添加一个类给克隆的li:

$(this).closest('li').clone().addClass("new-item").appendTo('#cart ul');
Run Code Online (Sandbox Code Playgroud)

然后设置一些样式,如:

.new-item img, .new-item li { height: 40px; width: 40px; }
.new-item h5 { display: none }
Run Code Online (Sandbox Code Playgroud)


dou*_*uwe 15

不幸的是,在dom操作中添加回调并不是可以用javascript以简洁的方式完成的.出于这个原因,它不在jQuery库中.但是,定时器"1ms"的settimeout总是将函数置于调用堆栈底部的settimeout中.这确实有效!underscore.js库在_.defer中使用这种技术,它完全符合你的要求.

$('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);
});
Run Code Online (Sandbox Code Playgroud)

  • DOM操作是同步的,没有理由"_.defer"任何东西 (3认同)