删除并再次添加后如何使该功能起作用

删除并再次添加后如何使该功能起作用

我不确定正确的标题是什么。我的问题是单击并更改标题后,它不再启动on click

请查看下面的小提琴:

Fiddle

的HTML

<h2><span class="ss-icon ss-repeat"></span>
        <span id="campaignEditTitle">Click Me to Edit <small><span class="ss-write"></span></small></span>
        <small> &nbsp; 3 Messages (2 active, 1 draft)
        </small>
      </h2>


JS

$('#campaignEditTitle').on('click', function(){
        var title = $(this).text();
        $(this).replaceWith('<input id="campaignInputTitle" type="text" value="' + title + '">');
        console.log(title);

        $('#campaignInputTitle').keypress(function(e) {
            if(e.which == 13) {
                var newTitle = $(this).val();
                $(this).replaceWith('<span id="campaignEditTitle">' + newTitle + '<small><span class="ss-write"></span></small>');
            }
        });
        $('#campaignInputTitle').on('blur', function(){
            var newTitle = $(this).val();
            $(this).replaceWith('<span id="campaignEditTitle">' + newTitle + '<small><span class="ss-write"></span></small>');
        });
    });

最佳答案

通过使用事件委托:

$('body').on('click','#campaignEditTitle', function(){
    var title = $(this).text();
    $(this).replaceWith('<input id="campaignInputTitle" type="text" value="' + title + '">');
    console.log(title);

});

$('body').on('keypress','#campaignInputTitle',function(e) {
        if(e.which == 13) {
            var newTitle = $(this).val();
            $(this).replaceWith('<span id="campaignEditTitle">' + newTitle + '<small><span class="ss-write"></span></small>');
        }
});

$('body').on('blur','#campaignInputTitle', function(){
        var newTitle = $(this).val();
        $(this).replaceWith('<span id="campaignEditTitle">' + newTitle + '<small><span class="ss-write"></span></small>');
});

关于javascript - 删除并再次添加后如何使该功能起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28426641/

10-13 23:32