且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Jquery - 追加后执行回调

更新时间:2023-12-04 23:08:52

jQuery 的 .each() 接受一个回调函数并将其应用到 jQuery 对象中的每个元素.

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

想象一下:

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

我还建议您不要像那样修改 CSS,而是像这样向克隆的 li 添加一个类:

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 }