我有一个JS函数,它执行AJAX调用来检索一些HTML数据,然后刷新<div>以及检索到的数据。
在刷新<div>内容,我想在调用JS函数之前,将光标替换在用户关注的任何元素中。
这是一个更大的函数的一部分,因此,为了简单起见,我只包含了我认为相关的代码:
$.ajax({
type: "POST",
url: "js/v_record_refresh_ajax.php",
data: {
filter: filter,
sort: sort_Val
},
cache: false,
success: function(data) {
// the following works perfectly
$('#volCard-'+filter).html(data);
if (msg.length > 0) {
$('#'+msg_div).html(msg);
}
// end of working code
console.log("Focus on element:");
console.log(activeEle.id); // activeEle is the HTML element I want to focus on
activeEle.focus(); // this does not appear to be working!
// the following code (intended to place the cursor at the correct position) is also not working, probably because I am failing to focus on the active element above.
// ta is a boolean indicating that the active element is either a text input or a textarea
if (ta) {
console.log("Put cursor at position:");
console.log(startPos + ":" + endPos);
activeEle.selectionStart = startPos; // this does not appear to be working!
activeEle.selectionEnd = endPos; // this does not appear to be working!
// alternative approach
//curActive.setSelectionRange(startPos, endPos);
}
},
error: function(xhr, status, error) {
console.error(xhr);
console.error(status);
console.error(error);
}
});
以下是控制台输出:
Focus on element:
sname-1
Put cursor at position:
0:11
请注意,sname-1是我试图关注的元素(文本输入)的id。
我还没有包括将这个元素分配给activeEle对象的代码,但我希望这个控制台输出证明activeEle是正确分配的。
我已经考虑到这可能是某种时间问题,并尝试在关注activeEle对象之前引入延迟,但这并没有帮助(我仍然没有关注activeEle对象-“sname-1”):
success: function(data) {
$('#volCard-'+filter).html(data);
if (msg.length > 0) {
$('#'+msg_div).html(msg);
}
setTimeout(function(){
console.log("Focus on element:");
console.log(activeEle.id);
activeEle.focus();
if (ta) {
console.log("Put cursor at position:");
console.log(startPos + ":" + endPos);
activeEle.selectionStart = startPos;
activeEle.selectionEnd = endPos;
//curActive.setSelectionRange(startPos, endPos);
}
}, 500);
},
我不确定如何解决此问题,因为我似乎拥有所有必要的元素:
我在控制台中没有得到任何错误,(显然)我没有把注意力集中在sname-1元素上。