自动完成谷歌地图JS错误

时间:2017-02-01 00:37:46

标签: javascript jquery google-maps

我一直在努力让自动完成功能与类名一起工作,虽然我已经这样做了,我不能再添加事件监听器了?任何人都有解决方案吗?

这是我的代码

const moodList = {
sad: [
    '"Dream as if you\'ll live forever, live as if you\'ll die today." James Dean',
    '"Life is a journey, and if you fall in love with the journey, you will be in love forever." Peter Hagerty',
    '"I\'ve learned that people will forget what you said, people will forget what you did, but people will never forget how you made them feel." Maya Angelou'
],
angry: [
    '"For every minute you remain angry, you give up sixty seconds of peace of mind."Ralph Waldo Emerson',
    '"Speak when you are angry - and you\'ll make the best speech you\'ll ever regret." Laurence J. Peter',
    '"Anger and intolerance are the enemies of correct understanding."Mahatma Gandhi'
]}

1 个答案:

答案 0 :(得分:3)

在循环中,您将重新分配autocomplete变量,但您只是将侦听器附加到最后一个变量,因为它位于循环之外。要为每个人提供一个监听器,你需要在循环中使用它。

function InitiliazeGoogleSearch() {
    var input = document.getElementsByClassName('js-autocomplete');
    for (var i = 0; i < input.length; i++) {
        autocomplete = new google.maps.places.Autocomplete(input[i]);

        google.maps.event.addListener(autocomplete, 'place_changed', function() {
            if (!$('.js-main-filter_wrapper').css('display', 'block')) {
                $('.js-main-filter_wrapper').slideToggle();
            }
        });
    }
}