简体   繁体   English

元素移除后的jQuery焦点

[英]jQuery focus after element removal

I have some contenteditable paragraphs that I would like to remove if the delete or backspace key is pressed. 如果按下删除或退格键,我想删除一些可编辑的段落。 I've written the following script for this: 我为此编写了以下脚本:

$(document).on('keyup', 'p[contenteditable="true"]', function(e) {
    if(e.which == 13) {
        e.preventDefault();
        $(this).after('<p contenteditable = "true">New Paragraph</p>');
        $(this).next('p').focus();
    } else if((e.which == 8 || e.which == 46) && $(this).text() == "") {
        e.preventDefault();
        $(this).remove();
        $(this).previous('p').focus();
    };
});

I would like to focus on the previous paragraph after removal but I don't believe I can do this as this no longer exists. 删除后,我想重点关注上一段,但是我不相信我可以这样做,因为this已经不存在了。 I've also tried putting the focus before remove however it appears to change the value of this . 我也尝试过将focus移到remove之前,但是似乎改变了this的值。

Try something like this: 尝试这样的事情:

$(document).on('keyup', 'p[contenteditable="true"]', function(e) {
    if(e.which == 13) {
        e.preventDefault();
        $(this).after('<p contenteditable = "true">New Paragraph</p>');
        $(this).next('p').focus();
    } else if((e.which == 8 || e.which == 46) && $(this).text() == "") {
        e.preventDefault();
        var prev = $(this).prev('p');
        $(this).remove();
        prev.focus();
    };
});

Also worth noting that .previous() is not a jQuery method, I believe the method you are looking for is .prev() 还值得注意的是.previous()不是jQuery方法,我相信您正在寻找的方法是.prev()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM