簡體   English   中英

setSelectionRange 未按預期工作

[英]setSelectionRange is not working as expected

我有以下問題,我收到以下錯誤

未捕獲的類型錯誤:$(...).setSelectionRange 不是函數

除了在一種情況下,該代碼幾乎 99% 的時間都可以工作,我無法弄清楚原因。

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

setSelectionRange是輸入元素的特定方法,而不是 jQuery 實例。 為此,您必須使用 vanilla JS 選擇器。

此外,您發布的代碼對范圍的開始和結束使用相同的值:

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

該代碼基本上將選擇從字符串中的最后一個字符開始,並將選擇結束設置為最后一個字符,因此實際上沒有選擇任何內容。

最后,您必須先聚焦輸入,然后才能設置選擇范圍。

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

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

檢查文檔和 MDN:

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

這是一個實時示例,它還有香草版本以防萬一:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM