javascript - jQuery,remove 并没有删除子元素,只是删除了父元素

标签 javascript jquery

我有一个函数,可以在单击事件时将元素附加到正文。然后,当单击先前附加的元素之一时,还有另一个应该删除这些元素。

当我单击 .closeBigPic 时,该元素会按预期删除,但 .bigPicWrapper div 会被删除,而 .bigPic 元素会保留在后面。

$(document).on('click', '.user-profile .avatar_section', function() {
    var thumbUrl = $(this).find('.avatar_profile').attr('src');

    var origUrl = thumbUrl.replace('thumb', 'medium');
    console.log(origUrl);

    $('body').append('<div class="closeBigPic"></div><div class="bigPicWrapper"><img class="bigPic" src="' + origUrl + '" /></div>')
});


$(document).on('click', '.closeBigPic', function() {
    $(this, '.bigPicWrapper').remove();
});

不知道为什么有必要,但这里是 scss 以防万一:

    .user-profile {
    .avatar_section {
        cursor: pointer;
    }
}

.bigPicWrapper {
    position: absolute;
    z-index: 9010;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);

    img {
        max-width: 100%;
        border-radius: 100%;
        border: solid 5px #fff;
    }
}

不应该 .remove() 也删除子元素。

更新:

当我将第二个点击事件更改为:

$(document).on('click', '.closeBigPic', function() {
    $(this).remove();
    $('.bigPicWrapper').remove();
});

它的工作原理与预期完全一致。那里发生了什么事?我想这与与this

结合有关

最佳答案

$(document).on('click', '.closeBigPic', function() {
  $(this, '.bigPicWrapper').remove();
});

这表示使用 .bigPicWrapper 作为上下文。是这样的

$('.foo, .bar').remove();

只是充当 CSS 选择器。

关于javascript - jQuery,remove 并没有删除子元素,只是删除了父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42941426/

相关文章:

javascript - document.ready 不工作。没有控制台错误并且包含 jQuery

javascript - 在 highcharts 图表中将平均值显示为列

javascript - 用动画滚动到中心

javascript - 使用链接在div内滚动div?

javascript - 客户端在 <li> 标签值内排序

javascript - 如何迭代数组值的字典来渲染组件? ReactJS

javascript - 在javascript中用天数计算月份

javascript - jQuery.ajaxSetup() 被忽略

javascript - 背景图像、3 个透明 png 按钮、三个链接和响应式。可能的?

javascript - 了解何时清除输入框并插入新输入