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

Calling java script function from different tags

本文关键字:java 脚本 函数 调用 标签      更新时间:2023-09-26

我有以下代码:

<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>

它写在html的body标签内。是否可以调用一个名为 initialize() 的 js 函数,它写在 html 页面的 head 标签中?如果是,如何?

编辑

初始化代码()

<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

是一个本地文件,最初什么都不包含,但在点击事件时包含各种位置的geojson格式的值

是否可以调用一个名为 initialize() 的 js 函数,它写在 html 页面的 head 标签中?

是的。

如果是,如何?

假设它是一个全局函数:

initialize();

页面中的所有脚本都放在一个大命名空间中。单个脚本不会彼此隔离,除非将它们包装在作用域函数中。所以:

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

。工作得很好。(脚本是内联的还是引用外部.js文件并不重要。