首页 > 解决方案 > 在同一函数中停止 onclick() 事件

问题描述

我一直在网上研究这个问题 2 小时(包括梳理其他 SO 问题),但我似乎找不到答案,所以这是不得已而为之。为了完整起见,我添加了整个函数,因为它只有 100 多行。

快速总结:我有一个按钮,用户单击该按钮以启动一个名为measure的函数,该函数具有 if/else 语句。当条件为真时,将启动两个 onclick() 函数。(函数ab)。

当条件为假时(再次单击按钮),else部分被正确触发(我验证了这一点)......我还希望 onclick 功能停止。但是,它们会永远持续下去。我曾尝试使用 stopPropogation() 但这似乎无济于事,并且功能仍在继续。我已经在评论中指出这是在哪里。

我究竟做错了什么?跳到else语句以快速查看我的问题。(非常底部)。

function measure()
{


    if (ims_measure==0) // if variable is 0 (or "off"), set it to 1 (on) and add layers along with onclick() events
    {
        ims_measure=1;
        document.getElementById("cpanel_measure").src = "images/cpanel_measure.png";
        map.setLayoutProperty('measure-points', 'visibility', 'visible');
        map.setLayoutProperty('measure-lines', 'visibility', 'visible');
        measuring_tool_menu = "Measuring Tool (mi.)<br>";


        var distanceContainer = document.getElementById('distance');

        // GeoJSON object to hold our measurement features
        var geojson_measure = {
            'type': 'FeatureCollection',
            'features': []
        };

        // Used to draw a line between points
        var linestring = {
            'type': 'Feature',
            'geometry': {
                'type': 'LineString',
                'coordinates': []
            }
        };


        map.addSource('geojson_measure', {
            'type': 'geojson',
            'data': geojson_measure
        });

        // Add styles to the map
        map.addLayer({
            id: 'measure-points',
            type: 'circle',
            source: 'geojson_measure',
            paint: {
                'circle-radius': 2,
                'circle-color': '#ffcc33'
            },
            filter: ['in', '$type', 'Point']
        });
        map.addLayer({
            id: 'measure-lines',
            type: 'line',
            source: 'geojson_measure',
            layout: {
                'line-cap': 'round',
                'line-join': 'round'
            },
            paint: {
                'line-color': '#ffcc33',
                'line-width': 2.5
            },
            filter: ['in', '$type', 'LineString']
        });


// First onclick function below (a)

        map.on('click', function(a) {



            var features = map.queryRenderedFeatures(a.point, {
                layers: ['measure-points']

            });

            // Remove the linestring from the group
            // So we can redraw it based on the points collection
            if (geojson_measure.features.length > 1)
                geojson_measure.features.pop();

            // Clear the Distance container to populate it with a new value
            distanceContainer.innerHTML = '';

            // If a feature was clicked, remove it from the map
            if (features.length) {
                var id = features[0].properties.id;
                geojson_measure.features = geojson_measure.features.filter(function(point) {
                    return point.properties.id !== id;
                });
            } else {
                var point = {
                    'type': 'Feature',
                    'geometry': {
                        'type': 'Point',
                        'coordinates': [a.lngLat.lng, a.lngLat.lat]
                    },
                    'properties': {
                        'id': String(new Date().getTime())
                    }
                };

                geojson_measure.features.push(point);
            }

            if (geojson_measure.features.length > 1) {
                linestring.geometry.coordinates = geojson_measure.features.map(function(
                point
                ) {
                    return point.geometry.coordinates;
                });

                geojson_measure.features.push(linestring);


                // Populate the distanceContainer with total distance
                var value = document.createElement('pre');
                value.textContent =
                'Total distance: ' +
                turf.length(linestring, {units: 'miles'}).toLocaleString() +'mi';
                distanceContainer.appendChild(value);


            }

            map.getSource('geojson_measure').setData(geojson_measure);
        });



        // Second onclick function below (b)
        map.on('mousemove', function(b) {


            var features = map.queryRenderedFeatures(b.point, {
                layers: ['measure-points']
            });
            // UI indicator for clicking/hovering a point on the map - Can't use because inable to change back?!
            //  map.getCanvas().style.cursor = features.length
            //  ? 'pointer'
            //  : 'crosshair';
        });



    }
    else {
        ims_measure=0;

        document.getElementById("cpanel_measure").src = "images/cpanel_measure_dark.png";
        map.setLayoutProperty('measure-points', 'visibility', 'none');
        map.setLayoutProperty('measure-lines', 'visibility', 'none');
        map.removeLayer("measure-lines");
        map.removeLayer("measure-points");
        map.getSource('geojson_measure').setData("");
        map.removeSource("geojson_measure");
        document.getElementById("distance").innerHTML = " ";
        measuring_tool_menu = "null";


       // here is where I wish to stop the onclick functions.
       // I have tried a.stopPropogation(), b.stopPropogation() as well as numerous other methods. None will seemingly do anything
       // as the onclick methods still fires as if I put no code here at all.


        return;
    }




}

标签: javascript

解决方案


要删除或分离事件功能,您可以使用以下提到的功能

移除 OnClick 事件

map.removeEventListener("click", function(e) { e.preventDefault(); }, false);

移除鼠标移动事件

map.detachEvent("onmousemove", function(e) { e.preventDefault(); });

点击此链接供您参考。


推荐阅读