简体   繁体   English

JS函数没有被调用

[英]JS function not being called

I'm a javascript new comer so I apologize in advance if this is a "newb" question. 我是一名Javascript新手,因此如果这是一个“新手”问题,我先向您道歉。

I'm making a web app that displays a google maps, map with a marker in your location. 我正在制作一个显示Google地图的网络应用,该地图在您的位置带有标记。 And then later more markers can be added to it using the add_marker function. 然后,可以使用add_marker函数向其添加更多标记。 A stripped down version of the code is: 该代码的简化版本为:

<!DOCTYPE html> 
<html> 
    <head> 
        <link rel="stylesheet" type="text/css" href="./common.css"/> 
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
        <script type="text/javascript" src=".\common.js"></script> 
        <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
        <script type="text/javascript">
        function add_stops(lat,lng)
        {
            var loc = new google.maps.LatLng(lat,lng);
            var marker = new google.maps.Marker
            ({
                position: loc,
                map: this.map,
                marker: marker
            });
        }
        </script>
        <title>Local Stops</title> 
    </head> 
    <body> 
        <div id="map_canvas"></div>
      <script type="text/javascript">initialize(null,null,16)</script> 
      <input type="button" id="10665"  value="Stop 10665" onmouseover="add_stops(49.89995, -97.14124, 10665)"/> 
      <script type="text/javascript">add_stops(49.89995, -97.14124)</script>
    </body> 
</html>

My problem is the add_stops function wont run when called in the script tags in the body but it works fine when called by the onmouseover event for the button. 我的问题是,在正文中的脚本标签中调用时,add_stops函数将不会运行,但是在按钮的onmouseover事件中调用时,它将正常运行。

In short what would cause a function to run from an event but not when called from the body, and what can I do to fix it. 简而言之,是什么导致事件从事件中运行,而从主体调用时却没有,我该怎么做才能修复它。

Thanks, any input is greatly appreciated. 谢谢,非常感谢任何输入。

**edited for spelling **针对拼写进行了编辑

Some external JavaScript functions are not yet fired when the page is loaded. 加载页面时,某些外部JavaScript函数尚未触发。 Try using setTimeout to delay the execution, eg fire your function after 5 seconds (5000) after page load, to give the chance for the Google's script to execute itself by that time. 尝试使用setTimeout延迟执行,例如,页面加载后5秒钟(5000秒)后触发函数,以便有机会让Google的脚本在该时间之前执行。

EDIT: code snippet. 编辑:代码段。 Something like: 就像是:

window.setTimeout(function() {add_stops(49.89995, -97.14124)}, 5000);
  <script type="text/javascript">add_stops(49.89995, -97.14124, 10665)</script>

This call has 3 parameters, your method definition has only two. 该调用有3个参数,您的方法定义只有2个。 Probably it has to do with that. 可能与此有关。

我猜您可以使用body标记的“ onload”事件来调用此函数,而不是编写用于调用它的脚本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM