消失的谷歌地图

Bun*_*bit 2 javascript google-maps

> <script type="text/javascript"
    src="http://maps.google.com/maps/api/js?sensor=true">
</script>
<script type="text/javascript">
  function initialize() {
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);
    marker = new google.maps.Marker({
    position : latlng,
    title : "hello world",
    draggable : true
    });
   marker.setMap(map)
  }
  function write(){
    //var positon = marker.getPosition()
    alert('position')
  }
</script>
</head>
<body onload="initialize()">
  <div id="map_canvas"></div>
  <input type='button' value ='position' onClick="write()">
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

每当我点击名为位置的按钮时,地图就会消失,为什么会这样呢?

bob*_*nce 15

+1 Jens的回答是正确的.不过说不write应该通常给你document.write.window属性作为全局变量,但document属性不起作用:

function write(){
    alert('position')
}

mybutton.onclick= function() {
    write(); // this is fine!
};
Run Code Online (Sandbox Code Playgroud)

诀窍在于,当您编写内联事件处理程序属性时,该元素及其祖先元素的属性将被转储到您的范围中.我不确定这实际上是在任何地方记录的,当然确切的行为会因浏览器而异,但它是一个古老的,完善的,非常危险的特性:

<input onclick="alert(value);" value="A"/>  // alerts A

<form method="get"><input onclick="alert(method)"/></form> // alerts get
Run Code Online (Sandbox Code Playgroud)

因为它document是页面中所有DOM节点的顶级祖先,

<div onclick="alert(write)"/> // alerts the `document.write` function
Run Code Online (Sandbox Code Playgroud)

这意味着您不能引用内联事件处理程序属性中的任何全局变量或函数,该属性恰好与祖先节点的成员具有相同的名称.由于新版本的浏览器一直在发布,引入新的DOM属性,因此在事件处理程序属性中对任何全局变量或函数的任何使用都可能在将来中断.

这是我们从不使用内联事件处理程序属性的另一个原因.

[所有这些例子假设alert解析为window.alert,即没有人碰巧将alert属性放在任何祖先DOM节点上......]