实现函数的JavaScript不会重复这些块中的所有内容 [英] JavaScript implementing a function to not repeat everything in those blocks

查看:71
本文介绍了实现函数的JavaScript不会重复这些块中的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我需要显示多个Google地图。我已经完成了这项工作( http://jsbin.com/arepaj/1/edit )以显示2张地图,但我觉得这是一种多次使用相同结构的肮脏方式。因为,我复制了两次相同的Google地图元素,以便能够显示两张地图。



如何动态创建多个Google地图,以便我只能通过位置坐标到该功能并创建多个地图。我最关心的是如何动态创建'div'标签来显示每个地图。

解决方案

您没有Maps API问题,您有JavaScript问题。这是一个很好的问题。



真正的问题是:我有两个非常类似的JavaScript代码块,有没有一种方法可以在不重复所有内容这些块?



答案是是的!把重复的代码放在一个函数中。

从jsbin获取代码并进行最简单的更改以将代码移动到常用函数中,您可以使用以下代码:

  function createMap(id,lat,lng){
var container = document.getElementById(id);
var center = new google.maps.LatLng(lat,lng);

var map = new google.maps.Map(container,{
zoom:10,
center:center,
mapTypeId:google.maps.MapTypeId.ROADMAP
});


函数初始化(){
createMap('map_canvas',48.1391265,11.580186300000037);
createMap('map_canvas2',46.702,11.678);
}

当然你可以从那里扩展它。还有其他的东西会不同于另一张地图?只需在函数中添加另一个参数。


In my application, I need to display multiple google maps. I have done this (http://jsbin.com/arepaj/1/edit) to display 2 maps, but I feel that it is kind of a dirty way using same structure many times. Because, I copied two times the same google maps elements to be able to display two maps.

How to create multiple google maps dynamically so that i can only pass the location coordinates to the function and create multiple maps. My biggest concern is here that how to create 'div' tags dynamically for displaying each map.

解决方案

You don't have a Maps API question, you have a JavaScript question. And it's a good question to ask.

The real question is: "I have two very similar blocks of JavaScript code. Is there a way to write this without repeating everything in those blocks?"

And the answer is "Yes! Put the repeated code in a function."

Taking your code from jsbin and making the simplest changes to move the code into a common function, you'd have something like this:

function createMap( id, lat, lng ) {
    var container = document.getElementById( id );
    var center = new google.maps.LatLng( lat, lng );

    var map = new google.maps.Map( container, {
        zoom: 10,
        center: center,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
}

 function initialize() {
    createMap( 'map_canvas', 48.1391265, 11.580186300000037 );
    createMap( 'map_canvas2', 46.702, 11.678 );
}

Of course you can extend it from there. Have something else that will be different from one map to the other? Just add another parameter to the function.

这篇关于实现函数的JavaScript不会重复这些块中的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆