简体   繁体   English

JS / jQuery>在附加输入中突出显示文本

[英]JS/jQuery > Highlight Text In Appended Imput

Upon clicking on my contextmenu menu (right-click custom menu), I have multiple cases set. 单击上下文菜单菜单(右键单击自定义菜单)后,我设置了多种情况。 The snippet below is the one set for renaming the folder (menu li > a value) which hides the link within the <li>...</li> and adds an input field. 下面的代码片段是用于重命名文件夹的一组代码(菜单li > a值),该文件夹将链接隐藏在<li>...</li>并添加一个输入字段。

$(document).ready(function() {
    "use strict";    

    $(document).on('mousedown', function(e) {
        if ($(e.target).parent().hasClass('custom-menu')) {
            switch (action) {
                case 'rename-folder':

                    anchor = clicked.find('a').first();
                    anchor.before($('<input />', {
                        type: 'text',
                        value: $(anchor).text(),
                        'class': 'FolderRenaming',
                        focusout: function() {
                            $(this).siblings('a').html($(this).val()).show();
                            $(this).remove();
                            $(anchor).parent().removeClass('clicked');
                        }
                    })).hide();
                    break;
            }
        }
    }).on('keyup', 'input.rename', function(e) {
        e.preventDefault();
        if (e.keyCode === 13) {
            $(e.target).focusout();
        }
    });
});

You right click and choose the option to 'rename'. 右键单击并选择“重命名”选项。 You've then got to click within this input field and either hit enter or outside of the field for the reverse to take place. 然后,您必须在此输入字段中单击,然后按Enter键或在该字段之外单击以进行相反操作。

How can I make it so upon clicking to rename, the text within the appended <input> is highlighted and therefore focused in? 在单击重命名后,如何做到这一点?附加的<input>的文本将突出显示并因此聚焦于此?

You can use the jQuery focus() function on an element to achieve this. 您可以在元素上使用jQuery focus()函数来实现此目的。

By changing your before() call, to an insertBefore() call, you can chain the focus() method onto the element you are appending. 通过将before()调用更改为insertBefore()调用,可以将focus()方法链接到要添加的元素上。

case 'rename-folder':

    anchor = clicked.find('a').first().hide();
    $('<input />', {
        type: 'text',
        value: $(anchor).text(),
        'class': 'FolderRenaming',
        focusout: function() {
            $(this).siblings('a').html($(this).val()).show();
            $(this).remove();
            $(anchor).parent().removeClass('clicked');
        }
    }).insertBefore(anchor).focus();
    break;

I haven't tested the above, as your code was just a snippet, but have created a basic implementation of the above here: https://jsfiddle.net/michaelvinall/w6q09rzs/1/ 我没有测试上面的代码,因为您的代码只是一个代码段,但是在这里创建了上面代码的基本实现: https : //jsfiddle.net/michaelvinall/w6q09rzs/1/

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

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