Javascript 函数返回函数代码行或“{[native code]},”我做错了什么?
我正在编写一些代码来在 contenteditable div 中查找用户选择,我从 获取代码这篇怪异模式文章。
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}
}
我正在 Chrome 和 Firefox 中测试它,如果我在函数内执行 alert(userSelection)
或在函数外部执行alert(findSelection();),它会返回 function getSelection() {[本机代码]}
。如果我这样做 console.log(findSelection();)
它会给我 getSelection()
。我是不是做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
getSelection 是一个函数...您需要执行它才能获得选择?
getSelection is a function... you need to execute it to get the selection?
将其更改为
if (window.getSelection) {userSelection = window.getSelection();}
(
getSelection
()
)Change it to
if (window.getSelection) {userSelection = window.getSelection();}
(
getSelection
()
)这是为了获取选择的文本。即使修复了拼写错误,您也会遇到不一致的行为:IE 将选择的文本作为字符串返回,而其他浏览器将返回一个
Selection
对象,该对象仅在其toString()
方法被调用。以下内容会更好:
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 itstoString()
method is called.The following would be better: