[英]How to focus on an input text with a value using jquery?
我试图创建一个类似于Google Keep的待办事项列表,当我专注于特定行并按以下键时:
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
}
});
我设法使Enter零件正常工作,但退格键无法正常工作。
应该做什么
当当前列表项为空时,它将删除该列表项并集中在上一个列表项上。
它实际上是做什么的
当前列表项为空时,它将删除列表项,并删除前一个列表项的值的最后一个字母
$(prevElement).focus();
被调用(我觉得很奇怪)。
您的退格操作仍然存在,您需要使用event.Handled = True来“取消”它。
您应该添加event.preventDefault();
在$(prevElement).focus();
。 这将防止删除上一项的最后一个字母。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.