简体   繁体   English

页面加载一次执行脚本

[英]Execute a script once on page load

I was messing about with some code but I am struggling a little bit to achieve what I want. 我当时在弄弄一些代码,但是我在努力实现自己想要的东西。 In the example here I have a map which displays when there are coordinates in my fields: 在这里的示例中,我有一个地图,该地图显示我的字段中何时有坐标:

http://jsfiddle.net/spadez/xJhmk/9/ http://jsfiddle.net/spadez/xJhmk/9/

// Generic Map Display
function mapDisplay() {

        var latval = $('#lat').val(),
            lngval = $('#lng').val();
        if ($.trim(latval) != '' && $.trim(lngval) != '') {
            var mapOptions = {
                zoom: 8,
                center: new google.maps.LatLng(latval, lngval),
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                disableDefaultUI: true,
                scrollwheel: false,
                draggable: false
            };
            var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
            $('#map_canvas').removeClass('hidden');
        } else {
            $('#map_canvas').addClass('hidden');
        }
    }

What I want to do is have this execute once per page, so that if there are values in the fields when the page loads then the map displays, but if the values get deleted after the page load or changes, the map will not change, since it read the variables at the start of ther page load only. 我想做的是让此操作每页执行一次,这样,如果页面加载时字段中有值,则地图会显示,但是如果值在页面加载或更改后被删除,则地图不会更改,因为它仅在页面加载开始时读取变量。

Can someone show me on my jsfiddle how that might be displayed please? 有人可以在我的jsfiddle上向我展示如何显示吗?

You are not calling the function mapDisplay(); 您未在调用mapDisplay();函数mapDisplay(); , on document ready call mapDisplay ,在文档就绪后调用mapDisplay

jQuery(function($){
    mapDisplay();
})

Demo: Fiddle 演示: 小提琴

window.onload = function(){

mapDisplay();

}

This runs your code on the onload event 这将在onload事件上运行您的代码

Use: 采用:

$(function()
{
    mapDisplay();
}  

// Generic Map Display
function mapDisplay() {

    var latval = $('#lat').val(),
        lngval = $('#lng').val();
    if ($.trim(latval) != '' && $.trim(lngval) != '') {
        var mapOptions = {
            zoom: 8,
            center: new google.maps.LatLng(latval, lngval),
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            disableDefaultUI: true,
            scrollwheel: false,
            draggable: false
        };
        var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
        $('#map_canvas').removeClass('hidden');
    } else {
        $('#map_canvas').addClass('hidden');
    }
}

You declare a function, and after page is loaded (the $(function() {} ), it is executed. 您声明一个函数,并在页面加载后($(function(){}),将其执行。

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

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