Javascript 使用jQuery动态添加元素的目标

Javascript 使用jQuery动态添加元素的目标,javascript,jquery,event-handling,dynamically-generated,event-delegation,Javascript,Jquery,Event Handling,Dynamically Generated,Event Delegation,我知道如何在jQuery上使用evenet委托。要监听一个偶数动态添加的元素,我必须使用以下命令 $('body .some-class').on('click', '.dynamically_added_ele', function(){}); 我很明白。谈到实际问题。假设我有一个按钮和DOM元素,我想动态地添加到文档中 <button class="my-button">Click Me</button> var newDom = '<p class="new

我知道如何在jQuery上使用evenet委托。要监听一个偶数动态添加的元素,我必须使用以下命令

$('body .some-class').on('click', '.dynamically_added_ele', function(){});
我很明白。谈到实际问题。假设我有一个按钮和DOM元素,我想动态地添加到文档中

<button class="my-button">Click Me</button>
var newDom = '<p class="new-dom">Hello there I am new content</p>';
点击我
var newDom='

您好,我是新内容

';
现在我正在绑定单击按钮上的事件以创建新元素

var allow = true;
$('.my-button').on('click', function(){
    var newDom = '<p class="new-dom">Hello there I am new content</p>';
    if( allow ) {
       $(this).after($(newDom));
    } else {
        $(newDom).remove(); // Not removing the new added element. Can't target that newly added element
    }
    allow = false;
});
var allow=true;
$('.my button')。在('click',function()上{
var newDom='

您好,我是新内容

'; 如果(允许){ $(this.after($(newDom)); }否则{ $(newDom).remove();//不删除新添加的元素。无法以新添加的元素为目标 } 允许=假; });
变量
允许
将检查为
,然后jQuery将创建该元素,最后一个
允许
变量将为
。再次使用时,单击该按钮allow将为
false
,此时jQuery应该删除新添加的元素。但在这里,我面临着问题。我不能像上面代码那样删除新添加的元素


我现在能做什么?

我必须像这样使用类选择器

var allow = true;
$('.my-button').on('click', function(){
    var newDom = '<p class="new-dom">Hello there I am new content</p>';
    if( allow ) {
        $(this).after($(newDom));
        allow = false;
    } else {
       $('.new-dom').remove();
       allow = true;
    }
 });
var allow=true;
$('.my button')。在('click',function()上{
var newDom='

您好,我是新内容

'; 如果(允许){ $(this.after($(newDom)); 允许=假; }否则{ $('.new-dom').remove(); 允许=真; } });
可能是这样的:

var allow=true;
var newDom=$(“

你好,我是新内容”

”; $('.my button')。在('click',function()上{ 如果(允许){ $(this).after(newDom); 允许=假; }否则{ newDom.remove(); 允许=真; } });


单击我
您试图在将其放入DOM之前将其删除,这是您的错误。为什么不使用类选择器删除所有“新dom”类元素$(“.new dom”).remove()@tanaydin我明白了,问题解决了。