简体   繁体   English

setSelectionRange 未按预期工作

[英]setSelectionRange is not working as expected

I have the following issue where I am getting the following error我有以下问题,我收到以下错误

Uncaught TypeError: $(...).setSelectionRange is not a function未捕获的类型错误:$(...).setSelectionRange 不是函数

The code works almost 99% of the time except in one situation, and I am not able to figure out why.除了在一种情况下,该代码几乎 99% 的时间都可以工作,我无法弄清楚原因。

 $(Id).setSelectionRange($(Id).val().length, $(Id).val().length);
 $(Id).focus();       

setSelectionRange is a specific method of an input element, not of a jQuery instance. setSelectionRange是输入元素的特定方法,而不是 jQuery 实例。 You have to use a vanilla JS selector for that.为此,您必须使用 vanilla JS 选择器。

Also the code you posted is using the same values for the start and end of the range:此外,您发布的代码对范围的开始和结束使用相同的值:

document.getElementById("yourInputId").setSelectionRange($(Id).val().length, $(Id).val().length)

That code basically sets the selection start at the last character in the string and the selection end to the last character as well, so nothing is actually selected.该代码基本上将选择从字符串中的最后一个字符开始,并将选择结束设置为最后一个字符,因此实际上没有选择任何内容。

Finally you have to focus the input before you can set the selection range.最后,您必须先聚焦输入,然后才能设置选择范围。

const myInput = $(Id);
const myInputValue = myInput.val();

myInput.focus();
myInput[0].setSelectionRange(0, myInputValue.length);

Check the docs and MDN:检查文档和 MDN:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange

Here is a live sample, it also has the vanilla version just in case:这是一个实时示例,它还有香草版本以防万一:

https://codepen.io/rhernando/pen/XWJodgp?editors=1010 https://codepen.io/rhernando/pen/XWJodgp?editors=1010

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM