如何使用jquery关注带有值的输入文本?

问题描述 投票:1回答:2

我正在尝试创建类似于Google Keep的待办事项列表,当我专注于特定行并按下时:

  1. 输入,它将创建一个新的列表项并将焦点转移到该列表项
  2. 退格时,它将删除当前列表项并关注前一项,假设有一个。

HTML

    <div class="col-sm-2">
        <h2>Plan</h2>
        <ul class="list-group list-group-sortable todo-list">

            @foreach (Models.ViewModels.PlanViewModel plan in Model.listPlan)
            {
            <li class="sortable list-group-item">
                <div class="d-inline">
                    <span class="text"><input id="@plan.Id" sort="@plan.Sort" class="plans" type="text" value="@plan.Description" /></span>
                    <span class="tools">
                        <i class="editPlan fa fa-thumb-tack"></i>
                        <i class="deletePlan fa fa-trash-o"></i>
                    </span>
                </div>
            </li>
            }
            <li class="list-group-item non-sortable disabled" style="height:55px;">
                <div style="float: right;">
                    <button id="savePlan" class="btn btn-info btn-group-sm">Save</button>
                    <button id="clearPlan" class="btn btn-default  btn-group-sm">Clear</button>
                </div>
            </li>
        </ul>
    </div>

使用Javascript

        $(document).on("keydown", "input.plans", function (event) {
            var KeyID = event.keyCode;

            //on keypress enter 
            if (KeyID == 13) {
                $('<li class="sortable list-group-item"><div class="d-inline"><span class="text"><input class="plans" type="text" /></span><span class="tools"><i class="editPlan fa fa-thumb-tack"></i><i class="deletePlan fa fa-trash-o"></i></span></div></li>').insertAfter($(this).parent().parent().parent()[0]);
                $(this).parent().parent().parent().next().find('input').focus();
            }
            //on keypress backspace
            else if (KeyID == 8 && $(this).val().trim() === '') {
                var prevElement = $($(this).parent().parent().parent().prev().find('input')[0]);
                $(this).parent().parent().parent().remove();
                $(prevElement).focus(); //This doesn't focus on previous List Item
            }
        });

我已设法使输入部分工作,但退格不能正常工作。

应该怎么做

当前列表项为空时,它将删除列表项并关注上一个列表项。

实际上是做什么的

当前列表项为空时,它将删除列表项并删除上一个列表项的值的最后一个字母

$(prevElement).focus(); 

被调用(我觉得很奇怪)。

javascript jquery
2个回答
1
投票

你应该在event.preventDefault();之后添加$(prevElement).focus();。这将阻止删除上一项的最后一个字母。

jQuery preventDefault documentation


1
投票

您的退格操作仍然存在,您需要使用event.Handled = True“取消”它

© www.soinside.com 2019 - 2024. All rights reserved.