繁体   English   中英

leaflet 标记和“onclick”事件的问题

[英]Problems with leaflet marker and the 'onclick' event

I am using PHP 7, leaflet 1.5.1 and I am looking to call an AJAX when the marker is clicked to display content in a different DIV than the map.

问题是 function 不等待“点击”,并在页面加载时自动激活,并在 DIV 中显示它侦听最后一个标记的参数。

然后当我点击一个标记时,当然什么也没有发生

想法?

剧本

<script src='https://code.jquery.com/jquery-3.4.1.js' integrity='sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=' crossorigin='anonymous'></script>
    <script>
     function mostrar2(id){
     var parametro = {id : id};
     $.ajax({
       data: parametro,
       url: 'elphp.php',
       type: 'post',
       beforeSend: function(){$("#panel").html("Thinking...");},
       success: function(response){$("#panel").html(response)}
       });        
     }
    </script>

听的 DIV

<div class="col-lg-3" id="panel">

MAP 分区

<div class="col-lg-9 map" id="map" style="width: 400px; height: 400px;">
 <script>
  var mymap = L.map('map').setView([51.505, -0.09], 13);
  L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
     maxZoom: 18,
     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>, ' +
                'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
     id: 'mapbox.streets'
}).addTo(mymap);

L.marker([51.5, -0.09]).addTo(mymap).on('click', mostrar2(15741));
L.marker([51.5, -0.99]).addTo(mymap).on('click', mostrar2('11'));

</script>
</div>

和 PHP

<?php
    $trajo = $_POST['id'];
    echo "YOU SENT : " . $trajo;
?>

这是它的样子

一位朋友通过这个简单的更改解决了这个问题。

问题: mostrar2 function被立即执行,并且因为 mostrar2 没有返回任何内容(隐式定义),所以没有在标记上注册的点击事件处理程序。

通过在匿名function中包装对mostrar2的调用,并将该 function 作为每个标记的单击事件处理程序传递,现在仅当在标记上触发单击事件并具有适当的 id 时才会发生mostrar2调用。

L.marker([51.5, -0.39]).addTo(mymap)
   .on('click', function () {
       mostrar2('15');
   }
);

暂无
暂无

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

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