如何在加载网页时运行脚本

how to run a script on loading a webpage

本文关键字:运行 脚本 网页 加载      更新时间:2023-09-26

如何在加载网页时运行此脚本,而无需按下按钮

    $(document).on('ready', function() {
    $('#findme').on('click', function() {    
    $('#message').html('Loading...');    
      $.ajax( {
        url: "https://api.mercadolibre.com/geolocation/whereami",
        success: function(data) {
          var city = data.city_name;
          var country = data.country_name;
          $('#message').text("You are in " + city + ", " + country + '!'); 
          }
      });
  });
});

你可以试试这个,它是你的代码,只是我删除了点击按钮功能,所以它将在文档准备功能上执行

$(document).on('ready', function() {
$('#message').html('Loading...');    
  $.ajax( {
    url: "https://api.mercadolibre.com/geolocation/whereami",
    success: function(data) {
      var city = data.city_name;
      var country = data.country_name;
      $('#message').text("You are in " + city + ", " + country + '!'); 
      }
  });
});

将代码放入函数中,并在所需事件中调用它。。。点击此处查看工作演示

$(document).on('ready', function() {
  geo();
});
$('#findme').on('click', function() {    
   geo();
});
function geo(){
  $('#message').html('Loading...');    
      $.ajax( {
        url: "https://api.mercadolibre.com/geolocation/whereami",
        success: function(data) {
          var city = data.city_name;
          var country = data.country_name;
          $('#message').text("You are in " + city + ", " + country + '!');  
        }
      });
}