按下 div 时,从我最后一个焦点文本字段中删除字符



我有一个div(按钮(,按下它时会删除特定文本字段的字符。现在,我正在尝试以删除最后一个焦点文本字段的字符的方式更改代码。

这是仅删除一个文本字段的字符的代码:

$(".delete").on("mousedown",function(evt) {
var nameInput = document.querySelector("#name")
var cursorPosition = nameInput.selectionStart;
$("#firstName").val(
function(index, value){
return value.substr(0,cursorPosition - 1) + value.substr(cursorPosition);
});
nameInput.selectionStart = cursorPosition - 1;
nameInput.selectionEnd = cursorPosition - 1;
return false;
});

这就是我现在所拥有的:

$(".delete").on("mousedown",function(evt) {
var lastFocused;
$(".item").focusout( function(e) {
lastFocused = e.target;
});
var cursorPosition = lastFocused.selectionStart;
lastFocused.val(
function(index, value){
return value.substr(0,cursorPosition - 1) + value.substr(cursorPosition);
});
lastFocused.selectionStart = cursorPosition - 1;
lastFocused.selectionEnd = cursorPosition - 1;
return false;
});

该 HTML:

<div class="delete key-btn">
<input id="firstName" name="firstName" type="text" class="item" required/>
<input id="firstName" name="firstName" type="text" class="item" required/>

在控制台中,我收到错误:"无法读取未定义的属性'选择开始'"。有人可以告诉我如何实现这一点吗?谢谢

这有效:

// 1. this has to be declared globally
var lastFocused;
// 2. you need to set the event handler for the 'item' elements outside of the delete handler
//    I'd also suggest using the 'focus' event here instead of 'focusout'
$(".item").focus(function(e) {
lastFocused = e.target;
});
$(".delete").on("mousedown", function(evt) {
// 3. need the null check if none of the inputs have been focused yet
if (!lastFocused) {
return;
}
var cursorPosition = lastFocused.selectionStart;
// 4. need to wrap this in the jQuery function to use val()
$(lastFocused).val(
function(index, value){
return value.substr(0,cursorPosition - 1) + value.substr(cursorPosition);
});
lastFocused.selectionStart = cursorPosition - 1;
lastFocused.selectionEnd = cursorPosition - 1;
return false;
});

您可以将目标返回给 lastFocus 的变量,您的删除函数应该可以工作。 我不确定你的其余代码是什么样子的,但这是我对你正在寻找什么的最佳猜测。 这将消除错误,您可以记录最后专注。

lastFocused = $(".item").focusout( function(e) {
return e.target;
});

我用代码解释得更好。

var focusedItems = [];
$('.item').on('focusin', function() { focusedItems.push( $(this) ); }
$('.item').on('focusin', function() { focusedItems.splice( $(this), 1 ); }
$('.delete').on('mousedown', function(evt) {
var lastFocused = focusedItems[ focusedItems.length - 1 ];
// do whatever you want
}

当您专注于作为 jquery 引用推送到数组中的项目时,当您专注于它时,您会将其删除。最后一个元素是最后一个焦点。

最新更新