Jquery - 追加后执行回调

问题描述 投票:30回答:4

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

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

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

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

jquery callback append live
4个回答
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'});
  });
});

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

$('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'});
});

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

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

然后设置一些样式,如:

.new-item img, .new-item li { height: 40px; width: 40px; }
.new-item h5 { display: none }

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);
});

4
投票

你可以继续在分号上继续操作。

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

等等


0
投票

在jquery中,您可以在添加内容代码后使用$()。这样,您可以确保在对附加内容执行任何任务之前加载内容并准备好DOM。

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

$()调用一个函数,该函数注册一个DOM-ready回调函数(如果函数传递给它)或者从DOM返回元素(如果选择器字符串或元素传递给它)

你可以在这里找到更多 difference between $ and $() in jQuery http://api.jquery.com/ready/

© www.soinside.com 2019 - 2024. All rights reserved.