微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

传单地图标记 onclickevent 无法按预期工作

如何解决传单地图标记 onclickevent 无法按预期工作

我为数组“starts”中的每个元素添加一个标记“beginPoint”。初始化网页时,onclick 函数会按顺序为每个标记运行,而我没有点击它们(这不是故意的)。

onclick 函数向我的 API 发送请求,该请求将返回与被点击的标记相关联的“轨道”的数据。最后这个数据被注入到我的 html 页面中。

因此,我的问题是,当我点击一个制造商时,onclick 功能似乎没有触发,但在为所有制造商加载页面时运行。提前致谢!

    //marker at the beginning of each track
    var starts = Object.values(starts);
    starts.forEach(function (element){
        var latlng = new L.LatLng(element.Latitude,element.Longitude);
        var beginPoint = L.marker(latlng,{icon:beginIcon}).addTo(mymap);
        beginPoint.on('click',onClick(element.id));
    });

}

//function called when clicking on marker @home
function onClick(e) {

    var request = {
      id: e
    };

    var url = "api/tracks/select"

    fetch(url,{
            method: 'post',headers: {'Content-type':'application/json'},body: JSON.stringify(request)
        }
    )
        .then(response => response.json())
        .then(json => insertTrackDetails(json));
}

// set the data corresponding to the selected track
// to the details field in the home view
function insertTrackDetails(data){

    var data = Object.values(data);
    var image = data[0].image;
    image = image.replace('public/images','/storage/images');

    document.getElementById('pills-detail').innerText = data[0].description;
    document.getElementById('pills-image').src = image;

    //Todo document.getElementById('pills-comments').innerText = data.description;
}

解决方法

当您使用 .on()() 中添加函数时,它会立即执行,而不是在单击时执行。 所以把这个beginPoint.on('click',onClick(element.id));改成这个 beginPoint.on('click',onClick);

那么你就遇到了如何知道 id 的问题。将 id 添加到标记中,然后读出:

starts.forEach(function (element){
        var latlng = new L.LatLng(element.Latitude,element.Longitude);
        var beginPoint = L.marker(latlng,{icon:beginIcon}).addTo(mymap);
        beginPoint.elmId = element.id; // store the id on the marker
        beginPoint.on('click',onClick);
    });
...


//function called when clicking on marker @home
function onClick(e) {
    var id = e.target.elmId; // readout the id from the marker
    var request = {
      id: id
    };
    ...

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。