简体   繁体   中英

initialization a function once in jquery

i have multiple google maps in one web page like below

<div class="map_wrapper">
    <div class="map_heading"><h2>Map1</h2><a href="#" class="map_link">Map Show</a></div>
    <div class="map_canvas">map parameters goes here</div>
</div>
<div class="map_wrapper">
    <div class="map_heading"><h2>Map1</h2><a href="#" class="map_link">Map Show</a></div>
    <div class="map_canvas">map parameters goes here</div>
</div>
<div class="map_wrapper">
    <div class="map_heading"><h2>Map1</h2><a href="#" class="map_link">Map Show</a></div>
    <div class="map_canvas">map parameters goes here</div>
</div>

i am using google maps v3, and the map function works well, i have function maps_init();

so i use jquery

in this way

$(document).ready(function(){
$(".map_link").click(function(){
        $(this).parent().parent().children(".map_canvas").slideToggle(100);
        var map = $(this).parent().parent().children(".map_canvas");
        maps_init(map);
    });
});

how can i make this work when i click the link then it call the function otherwise never call again that function, because user can click the "map_link" to see multiple times and every time it initializes the function, so i need the reference in every div "map_wrapper" for it's own which will check. if not initialized then it will initialize otherwise not, i can not use in map_init() function in document.ready() because it initializes all the maps and maps does not looks correctly.

Thanks!

You could add a class to keep track of the initialized maps:

$(".map_link").click(function(){
        if(!($(this).hasClass('initialized')) {
            $(this).parent().parent().children(".map_canvas").slideToggle(100);
            var map = $(this).parent().parent().children(".map_canvas");
            maps_init(map);
            $(this).addClass('initialized');
        }
    });
});

Might not be the cleanest solution but I guess it's simple and fast

OR

you could use jQuery's "one" method, which will fire only once:

http://jsfiddle.net/jonigiuro/WQPjn/

$('a').one('click', function(e) {
    alert('map initialized');
    e.preventDefault();
});

in your case:

$(document).ready(function(){
$(".map_link").one('click',function(){
        $(this).parent().parent().children(".map_canvas").slideToggle(100);
        var map = $(this).parent().parent().children(".map_canvas");
        maps_init(map);
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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