【发布时间】:2017-08-11 23:51:59
【问题描述】:
我有 3 张图片
<img>
<img>
<img>
当我删除图像时
$('img:nth-child(1)').remove();
然后添加另一个。
$( '.hero .trim').append($img);
然后尝试再次删除第一个
$('img:nth-child(1)').remove();
它不起作用。如何让它工作,以便新图像是第一个孩子?
编辑完整代码...
function completeIt () {
$('.hero .trim img:nth-child(1)').remove();
};
if(this.talentClick == false) {
//$('.hero .trim img').append('<img>').attr('src', '/img/headers/'+deptname+'-header-mobile.jpg').attr('data-mobile', '/img/headers/'+deptname+'-header-mobile.jpg').attr('data-tablet', '/img/headers/'+deptname+'-header-tablet.jpg').attr('data-desktop', '/img/headers/'+deptname+'-header.jpg')
let img = '';
let width= $(document).width();
var $img = $('<img />').attr('src', '/img/headers/'+deptname+'-header.jpg').attr('data-mobile', '/img/headers/'+deptname+'-header-mobile.jpg').attr('data-tablet', '/img/headers/'+deptname+'-header-tablet.jpg').attr('data-desktop', '/img/headers/'+deptname+'-header.jpg')
$( '.hero .trim').append($img);
let firstimgheight = $('.hero .trim img:nth-child(1)').height();
let secondimgheight = $('.hero .trim img:nth-child(2)').height();
console.log($('.hero .trim img:nth-child(1)') );
tl.to( $('.hero .trim img:nth-child(1)'), 0.2, {css:{marginTop: -firstimgheight+"px"}})
.to($('.trim'), 1, {css:{height: secondimgheight+'px'}});
【问题讨论】:
-
调查事件委派,jQuery无法看到添加的元素。 span>
-
这只是为了说明的目的 - 有一个容器。这更像是关于jQuery如何在删除后处理nth-child的问题。 span>
-
问题是您的代码确实删除了第一张图片,但第一张图片不是您想要的特定图片吗?
-
“它不起作用” - 它有什么作用?你怎么称呼它?这里的一些 cmets 建议使用事件处理程序,但您没有提到您的代码是从单击事件或类似事件中调用的,那么您如何/何时调用第二次删除?
.hero .trim相对于其他 3 张图像在哪里。与同一容器中的其他3个图像是吗?如果您提供更多上下文会更容易。 -
我不确定使用您的代码是否有任何问题。您可能还有其他问题使其无法正常工作。查看工作示例:jsfiddle.net/r81fqe4m
标签: jquery dom jquery-selectors removechild