如何获取地图的父元素

时间:2019-04-26 18:15:59

标签: javascript html

我不想在以下代码中交出div的ID。是否可以在JavaScript函数中获取父元素的ID?

<link rel="stylesheet" href="../js/Leaflet/leaflet.css" >
<script src="../js/Leaflet/leaflet.js" ></script>
<script>
'use strict';
var osmUrl = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';

function show_karte(div_id, mittelpunkt, zoom){
var osmLayer = L.tileLayer(osmUrl, {maxZoom: 20, attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'});
var mittelpunkt = [mittelpunkt[1], mittelpunkt[0]]
var map = L.map(div_id,{layers: [osmLayer]}).setView(mittelpunkt, zoom};    
</script>

<body>
<div id="map" style="width:450px; height: 450px;">
    <script  type="text/javascript"> show_karte("map",[6.026173,50.816022],13); </script>
</div>
<div id="xyz"><p> some text </p></div>
<div id="map1" style="width:550px; height: 450px;">
    <script  type="text/javascript"> show_karte("map1",[6.10428,50.76079],11); </script>
</div>
<div id="map2" style="width:650px; height:450px">  
    <script  type="text/javascript">show_karte("map2",[6.10428,50.76079],12); </script>
</div>

2 个答案:

答案 0 :(得分:0)

一个选择是不以这种方式生成映射,而是循​​环遍历map类并从属性中提取数据。下面,我向每个div添加了map类,然后添加了纬度,经度和zoom作为数据属性。然后只需遍历它们并根据需要提取数据即可。

function  show_karte(id, pos, zoom){
console.log(id,pos,zoom);
}

var maps = document.getElementsByClassName("map");

for(var x = 0;x < maps.length;x++){
    let this_map = maps[x];
    
    show_karte(this_map.getAttribute('id'),[this_map.getAttribute('data-lat'),this_map.getAttribute('data-lon')],this_map.getAttribute('data-zoom'));
}
<div id="map" class="map" data-zoom="13" data-lat="6.026173" data-lon="50.816022" style="width:450px; height: 450px;"></div>

<div id="xyz"><p> some text </p></div>

<div id="map1" class="map" data-zoom="11" data-lat="6.10428" data-lon="50.76079" style="width:550px; height: 450px;"></div>

<div id="map2" class="map" data-zoom="12" data-lat="6.10428" data-lon="50.76079" style="width:650px; height:450px"></div>

答案 1 :(得分:0)

您需要搜索实际的脚本元素(在您的情况下,也许div就足够了),可以从其父元素中读取ID。

Obtain a reference to <script> parent element

var scriptTag = document.getElementsByTagName('script');
scriptTag = scriptTag[scriptTag.length - 1];
var parentDiv = scriptTag.parentNode;
var mapId = parentDiv.id;