简体   繁体   English

从不同的标签调用Java脚本函数

[英]Calling java script function from different tags

I have the following code: 我有以下代码:

<script src="jquery-1.10.2.min.js"></script>
<script>
$('#year li').click(function() {
    var text = $(this).text();
    //alert('text is ' + text);
    $.post("B.php", { text: text }, function(return_data, txtStatus, jqXHR) {
$('#result').html(return_data);
});

$.post("C.php", { text: text }, function(return_data, txtStatus, jqXHR) {
$('#subresult').html(return_data);
});
  event.preventDefault() ;
  });

</script>

It is written inside the body tag of html. 它写在html的body标签内。 Is it possible to call a js function called initialize() which is written inside the head tag of the html page? 是否可以调用一个称为initialize()的js函数,该函数写在html页面的head标签内? if yes how? 如果是,怎么办?

Edits 编辑

Code to initialize() 初始化代码

<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=visualization">
</script>
<script>
var map;

  function initialize() {
    var mapOptions = {
      zoom: 5,
      center: new google.maps.LatLng(2.8,-187.3),
      mapTypeId: google.maps.MapTypeId.TERRAIN
    };
    map = new google.maps.Map(document.getElementById('map_canvas'),
          mapOptions);
    var script = document.createElement('script');
    script.src = 'geojson';
    document.getElementsByTagName('head')[0].appendChild(script);
  }
  window.eqfeed_callback = function(results) {
    for (var i = 0; i < results.features.length; i++) {
      var coords = results.features[i].geometry.coordinates;
      var latLng = new google.maps.LatLng(coords[1],coords[0]);
      var marker = new google.maps.Marker({
        position: latLng,
        map: map
      });
    }
  }
</script>

geojson is a local file which initially contains nothing but upon the click event contains geojson formatted value of various locations geojson是一个本地文件,最初不包含任何内容,但单击事件后包含各个位置的geojson格式化值

Is it possible to call a js function called initialize() which is written inside the head tag of the html page? 是否可以调用一个称为initialize()的js函数,该函数写在html页面的head标签内?

Yes. 是。

if yes how? 如果是,怎么办?

Assuming it's a global function: 假设它是一个全局函数:

initialize();

All of the script in a page is put in one big namespace. 页面中的所有脚本都放在一个大命名空间中。 Individual scripts aren't isolated from one another unless you wrap them in scoping functions. 除非将单个脚本包装在作用域函数中,否则它们不会相互隔离。 So: 所以:

<head>
<!-- ... -->
<script>
function initialize() {
    alert("initialize!");
}
</script>
</head>
<body>
<script>
initialize();
</script>
<!-- ... -->
</body>
</html>

...works just fine. ...工作正常。 (And it doesn't matter whether the scripts are inline or refer to external .js files.) (并且脚本是内联脚本还是引用外部.js文件都没有关系。)

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

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