问题
I am writing some code to find the user selection in a contenteditable div, I'm taking my code from this quirksmode article.
function findSelection(){
var userSelection;
if (window.getSelection) {userSelection = window.getSelection;}
else if (document.selection){userSelection = document.selection.createRange();} // For microsoft
if (userSelection.text){return userSelection.text} //for Microsoft
else {return userSelection}
}
I'm testing it in Chrome and Firefox, if I do an alert(userSelection)
within the function or an alert(findSelection();) outside the function, it returns function getSelection() {[native code]}
. If I do console.log(findSelection();)
it gives me getSelection()
. Is there something I've done wrong?
回答1:
Change it to
if (window.getSelection) {userSelection = window.getSelection();}
(getSelection
()
)
回答2:
getSelection is a function... you need to execute it to get the selection?
if (window.getSelection) {userSelection = window.getSelection();}
回答3:
This is to get the text of the selection. Even with the typo fixed, you've got inconsistent behaviour: IE is returning the selection's text as a string while other browsers will return a Selection
object that will give you the selection text string only when its toString()
method is called.
The following would be better:
function getSelectionText(){
if (window.getSelection) {
return "" + window.getSelection();
} else if (document.selection && document.selection.createRange) {
return document.selection.createRange().text;
}
}
来源:https://stackoverflow.com/questions/2820650/javascript-functions-return-lines-of-function-code-or-native-code-what-am