使用 jQuery 定位动态添加的元素

Target dynamically added element using jQuery

我知道如何在 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 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;
});

variable allow 将检查为 true 然后 jQuery 将创建该元素,最后一个 allow 变量将是false。当再次使用单击该按钮时,允许将 false 并且该时间 jQuery 应该删除新添加的元素。但在这里我面临着问题。我无法像上面编码的那样删除新添加的元素。

我现在可以做什么?

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

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;
var newDom = $('<p class="new-dom">Hello there I am new content</p>');

$('.my-button').on('click', function(){
    if( allow ) {
       $(this).after(newDom);
       allow = false;
    } else {
        newDom.remove();
        allow = true;
    }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<button class="my-button">Click Me</button>