动态添加的元素不会删除

时间:2014-08-14 18:53:18

标签: javascript jquery html

为什么在此代码块中不会删除.mydiv img

$( document ).on( "click", '.onhover', function() {
    $('.mydiv img').remove();
    var clone = $('.onhover').clone();
    $('.mydiv').append(clone);
});

另外我应该补充一点,每张图片的src都是 base64 ,不确定这是不是问题。


编辑:.onhover html

<img class="onhover" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAYAAAD0eNT6AAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4A...Am1QaMG+m7GaFP+FMUDQBFHUkTMCkZGFdLgDklAJgAcjeFOZgU+RP+FEUDQFFH2gRgijRgmtH+bkb/s5iAaesECH+KogGgKJqAMdAfN1rf689tf2uSpk0CdlvYR/hTFA0ARR15EzDKGMw6TSCmSBVm1TiAzwJ6PwLwhD9F0QBQ1JEyAcDkKQFMMZqfFfzTLgPcTRowy6h/XBJA+FMUDQBFHWkTMM4AYIqUABMeexoT4KdMBMYZhEmjfsKfomgAKIomYMo0YNJof9bCv0lJwChoz3I/MEXkT/hTFA0ARR1FEzApDZhkGMYBfzcJwCzwngX8hD9F0QBQFE3AHI3AtKnCbkb/uxnRT/s4hD9F0QBQFNOAKW7vBvR7TQCmhf7M4Cf8KYoGgKJoAnZnBCb9m73WAEwLcoKfomgAKIqagwmYBPNZ/99x908z6p+XUSD8KYoGgKKoXRqBeY3095oMTDIBBD9FLaj+/wEAfEsmcAJIeAcAAAAASUVORK5CYII=" style="float:left; height: 100%; position: relative; width: 55px; margin-right: 4px;">

2 个答案:

答案 0 :(得分:1)

这可能是你想要的。

$('.onhover').on("click", function () {
    $('.mydiv').html($(this).clone());
});

fiddle here

修改

我这里有一个更新的代码,支持单个视图的thumnails和全尺寸图像:

http://jsfiddle.net/paoloposo/kqukymy3/5/

答案 1 :(得分:0)

删除前需要克隆。您还可以确保删除被点击的内容:

$( document ).on( "click", '.onhover', function() {
    var $this = $(this),
        $parent = $this.parent(),
        $clone = $this.clone();

    $this.remove();
    $parent.append( $clone );
});

编辑:假设.mydiv位于页面上的其他位置......可能是这样的:

<div class="mydiv"></div>

<div class="thumbnails">
    <img class="onhover" src="img1.jpg" />
    <img class="onhover" src="img2.jpg" />
    <img class="onhover" src="img3.jpg" />
</div>

...然后你会想要使用以下代码:

var $mydiv = $('.mydiv');
$( document ).on( "click", '.onhover', function() {
    var $clone = $(this).clone().removeClass('onhover');
    $mydiv.empty().append( $clone );
});