2010-12-09 42 views
0

是否有可能我可以在函數中使用charAt函數get選擇如下?javascript:是否有可能使用charAt函數來獲取選定的文本?

getSelected function() { 
    var userSelection; 
    if (window.getSelection) { 
     userSelection = window.getSelection(); 
    } else if (document.selection) { 
     userSelection = document.selection.createRange(); 
    } 
    userSelection return; 
} 

如: 我有一整段文字歡迎堆放超過流量,然後選定的文本是堆棧。如果系統找到相同的文本,系統會返回位置?如果系統找到相同的文本,我可以使用charAt來獲取指定的位置,當用戶選擇文本時,系統會將其與所有文本進行比較。

因爲在我認識的charAt函數可用於確定字符串的具體位置.. http://help.dottoro.com/ljetnrhv.php#charAt

回答

1

不是直接的,因爲這兩種方法返回一個對象,而不是字符串。要使用的charAt您需要獲得選擇的字符串值,沿

function getSelectionText() { 
    if (window.getSelection) 
     return window.getSelection().toString(); 
    if (document.selection) 
     return document.selection.createRange().text; 
    return null; 
} 

alert(getSelectionText().charAt(2)); // 3rd selected char 

線要查找某個字符串在另一字符串的位置使用indexOf。在頁面上查找選擇的位置要複雜得多,因爲您需要考慮html結構。瞭解更多,請致電herehere

+0

我可以得到具體的位置,如果我比較所選文字的值與所有文字? – user495688 2010-12-09 06:02:08

相關問題