日期:2014-05-16  浏览次数:20268 次

关于 !document.selection 的问题
从论坛看了段代码:


<input type="button" value="ShowDirection" onclick="ShowDirection(this)"/>

    function ShowDirection(btn) {
        var tbl = [];
        var direct = (document.selection && document.selection.createRange) 
                                         ? document.selection.createRange().parentElement() // IE
                                         : window.getSelection().focusNode.parentNode; //FF
  .....................
}


当打开页面或者刷新页面后,鼠标不在页面有任何点击之前,就开始点击ShowDirection按钮,将会提示:
Uncaught TypeError: Cannot read property 'parentNode' of null 

请问该如何解决呢? 
if(鼠标没有点击页面就开始点击这个按钮){提示: }



谢谢

------解决方案--------------------
这时候 focusNode 应该是 null,所以出错。把代码最后那部分改一下:

window.getSelection().focusNode?
   window.getSelection().focusNode.parentNode: null;

------解决方案--------------------
因为这时候 direct 获得的值是 null,所以后面代码使用它会出错。不妨在 do 前面加一行:

if (!direct) return;  // 如果 direct 无值,直接退出函数。

掌握一点:如果某对象 object 为 null,以 object.property 这种形式访问其成员就会出现你看到的错误。