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

时间:2015-04-03 08:43:29

标签: javascript

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

    $(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 + '!'); 
          }

      });
  });

});

3 个答案:

答案 0 :(得分:1)

将代码放入函数中并在所需的事件中调用它...... Check working demo here

$(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 + '!');  
        }
      });

}

答案 1 :(得分:1)

在第一个实例中,$(document).on('ready', function() { ... })的使用被弃用了(v1.8)。最好是:

$(document).ready(function() { ... })

$(window).on('load', function() { ... })

http://codepen.io/anon/pen/QwPzPK

答案 2 :(得分:0)

你可以试试这个,它的代码只有我点击功能上的删除按钮,所以它将在文件就绪功能上执行

$(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 + '!'); 
      }

  });
});