This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
                                
                                    (8个答案)
                                
                        
                                2个月前关闭。
            
                    
我有一个搜索输入,可在用户输入时在其下方的div中填充建议,我想在建议div中添加事件监听器。问题是页面加载建议div时未填充任何内容,因为用户尚未在搜索输入中键入任何内容,并引发


  TypeError:searchSugg未定义


有没有解决的办法?我尝试将监听器包装在if (searchSugg !== undefined) {...}中,尽管它不会引发错误,但是它也不会运行addEventListener函数。

码:

    var searchSugg = document.getElementsByClassName('mapboxgl-ctrl-geocoder--suggestion')[0];
    searchSugg.addEventListener('click', function() {
        // // Create variables to use in isochrone API
        var urlBase = 'https://api.mapbox.com/isochrone/v1/mapbox/';
        var lng = geocoder.mapMarker._lngLat.lng;
        var lat = geocoder.mapMarker._lngLat.lat;
        var profile = 'cycling';
        var minutes = 10;
        // Create a function that sets up the Isochrone API query then makes an Ajax call
            var query = urlBase + profile + '/' + lng + ',' + lat + '?contours_minutes=' + minutes + '&polygons=true&access_token=' + mapboxgl.accessToken;
                    $.ajax({
                    method: 'GET',
                    url: query
                    }).done(function(data) {
                        map.getSource('iso').setData(data);
                    })
        map.addSource('iso', {
            type: 'geojson',
            data: {
            'type': 'FeatureCollection',
            'features': []
            }
        });
        map.addLayer({
            'id': 'isoLayer',
            'type': 'fill',
            // Use "iso" as the data source for this layer
            'source': 'iso',
            'layout': {},
            'paint': {
            // The fill color for the layer is set to a light purple
            'fill-color': '#5a3fc0',
            'fill-opacity': 0.3
            }
        }, "poi-label");
    });

最佳答案

您可以在分配searchSugg处理程序之前检查click是否存在。



let searchSugg = document.getElementsByClassName("some-class-that-does-not-exist")[0];

searchSugg && searchSugg.addEventListener('click', event => {
  // click event handler code
});

// Or you can do
if (searchSugg) {
  searchSugg.addEventListener('click', event => {
    // click event handler code
  });
}

<p>Some Webpage</p>

10-07 17:32