Javascript 这是一个范围问题吗?

Javascript 这是一个范围问题吗?,javascript,jquery,Javascript,Jquery,我在卡片上加了一个关闭按钮。我尝试了这个代码,但是关闭按钮似乎不起作用 $('#add-pet').on('click', e => { // Grab info from the form let $name = $('#pet-name').val(); let $species = $('#pet-species').val(); let $notes = $('#pet-notes').val(); let $newPet = $(

我在卡片上加了一个关闭按钮。我尝试了这个代码,但是关闭按钮似乎不起作用

$('#add-pet').on('click', e => {

    // Grab info from the form
    let $name = $('#pet-name').val();
    let $species = $('#pet-species').val();
    let $notes = $('#pet-notes').val();

    let $newPet = $(
        '<section class="six columns"><div class="card"><p><strong>Name:</strong> ' + $name +
        '</p><p><strong>Species:</strong> ' + $species +
        '</p><p><strong>Notes:</strong> ' + $notes +
        '</p><span class="close">&times;</span></div></section>'
    );

    // Attach the new element to the page
    $('#posted-pets').append($newPet);

});
$('.close').on('click', function() {
    $(this).parent().remove();
});
就在
$('#posted pets')之后。append($newPet)
那就行了。

为什么会这样?

当close函数在div之外时,它试图附加到现有的
。close
元素,而您试图附加到的元素在该时间点不存在。您需要在内部执行此操作,因为您需要先实际创建
$newPet
元素,然后才能附加到它。

$('.close')
将在dom中搜索


如果您尚未附加html,那么无论何时您想要为可以通过jQuery附加的元素创建事件,jQuery都无法找到它,您可以尝试:

$(document).on('click', '.close', function() {
    $(this).parent().remove();
});
在添加
span.close
标记后,它会工作。即使超出范围

$('#add-pet').on('click', /*...*/);
更新:

您也可以尝试:

$('#add-pet').on('click', e => {
    let close_tag = $('<span>').addClass('close');

    // do stuff...

    // set event
    close_tag.on('click', function () {
        $(this).parent().remove();
    });

    $('#posted-pets').append(close_tag);

});
$('addpet')。在('click',e=>{
让close_标记=$('').addClass('close');
//做些事情。。。
//设置事件
关闭('click',函数(){
$(this.parent().remove();
});
$(“#已发布的宠物”).append(close#tag);
});

我认为代码$('.close').on('click',function(){$(this.parent().remove();});将搜索Dom,然后将remove函数附加到它。但是,您的意思是我需要在创建元素之前将其附加到元素,对吗?正确。您需要在创建元素之后运行它,在顶部示例中,它在创建之前运行。为什么需要添加类(“close”)?是否已具有该类?@AiNguyen
$(“”)
将创建没有类名的新span标记
addClass('close')
将class
close
添加到span标记中。这是创建新标记的另一种方法。与
$('#add-pet').on('click', e => {
    let close_tag = $('<span>').addClass('close');

    // do stuff...

    // set event
    close_tag.on('click', function () {
        $(this).parent().remove();
    });

    $('#posted-pets').append(close_tag);

});