简体   繁体   English

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

[英]how to run a script on loading a webpage

how can i get this script to run on loading a webpage , without pressing a button 我如何才能使此脚本在加载网页时运行,而无需按按钮

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

      });
  });

});

Put the code in a function and call it in desired events... 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 + '!');  
        }
      });

}

The use of $(document).on('ready', function() { ... }) was deprecated jQuery at the first instance it was possible (v1.8). 第一次使用jQuery(v1.8)时不推荐使用$(document).on('ready', function() { ... }) )。 It should better be : 最好是:

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

or 要么

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

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

you can try this, its your code only i removed button on click function so it will execute on document ready function 您可以尝试此操作,仅将您的代码删除。单击功能上的按钮已删除,因此它将在文档就绪功能上执行

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

  });
});

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

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