我有一个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/>
在控制台中,出现错误:“无法读取未定义的属性'selectionStart'。有人可以告诉我如何实现吗?谢谢
答案 0 :(得分:1)
这有效:
// 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;
});
答案 1 :(得分:0)
您可以将目标返回到lastFocused变量,并且删除功能应该可以正常工作。 我不确定其余的代码是什么样的,但这是我对所要查找内容的最佳猜测。这将消除错误,您可以登录lastFocused。
lastFocused = $(".item").focusout( function(e) {
return e.target;
});
答案 2 :(得分:0)
我用代码解释得更好。
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引用推入数组,而当您进行聚焦时则将其删除。最后一个元素是最后一个重点。