首页 > 解决方案 > add event to element after it remove itself and append itself again

问题描述

I tried to remove a button and alert() when i click it, then the function will append a 'same' button to a container div, after searching senior's legacy, i tried to use on()/live()/delegate()/ unfortunately they not work.

<body>
    <div id="container"></div>
    <hr>
    <button onclick="clicked()">Other one</button>
    <hr>
</body>
<script>
$(document).ready(function(){
    var i = 0;
    $("#container").append("<button id='btn_sub' onclick='clicked()'>Click Me!</button>");
    $("[id='btn_sub']").delegate(this,"click",function(){
        $("#container").empty();
        $("#container").append("<button id='btn_sub' onclick='clicked()'>Click Me!"+i+"</button>");
        i++;
    });//tried click/on click/live
});
function clicked(){
    alert(1);
}
</script>

Finally, in this example, the clicked function put out of $(document).ready() and the part of alert worked.

Is there any other method to do the same effect? and why on()/live()/delegate()/ not work?

Thanks.

标签: javascriptjquery

解决方案


First off $("[id='btn_sub']") can be replaced with $("#btn_sub"), then it's actually better to use a class as you might have many buttons.

This is a working example as an illustration: https://codepen.io/antoniandre/pen/XoNNpO

$(document).ready(function(){
    $("#container").on("click", '.btn_sub', function() {
        removeButton(this);
    });
});
function addButton() {
    $("#container").append("<button class='btn_sub'>Delete Me!</button>");
}
function removeButton(btn) {
    btn.remove();
}

With the on() bound on the container, you actually make sure any matching button .btn_sub will get this event attached to them when they are created in the future.

Regarding live, it does the same as on but is now deprecated so you can forget it. https://api.jquery.com/live/#live-events-handler


推荐阅读