javascript方法的方法名慎用close

    通常我们在定义了与window同名的方法时,会自动覆盖掉window同名的方法。close()方法也不例外。示例:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title></title>
    <script type="text/javascript">
        function close() {
            alert(1);
        }
    </script>
</head>
<body>
  <input type="button" value="确定" onclick="close()" />
</body>
</html>

      但是点击确定按钮,你会发现根本没按预期弹出“1”。这是因为我们定义的close方法虽然覆盖了window.close,但是document下还有一个close方法没被覆盖。为了覆盖document.close方法,我们需要添加一句代码:

document.close = close;

      再尝试一次成功!!!

      参考文档:https://segmentfault.com/q/1010000006560243

posted @ 2017-04-22 19:39  wangwust  阅读(181)  评论(0编辑  收藏  举报