Javascript函数调用内部下拉列表更改事件错误

时间:2018-03-06 09:30:01

标签: javascript jquery javascript-objects

var TourItinerary = {  
    EXCURSIONS:{

    },
    init:function(){
        console.log('Initializing...');
        this.initializeElements();
    },       
    initializeElements:function(){
        console.log('init elements...');
        $("select[id^='start_city_']").change(function(){
            var day_id = $(this).attr('id').replace("start_city_","");
            getPossibleExcursions(day_id);
        });
    },    
    getPossibleExcursions: function(day_id){
        console.log('Day Id ='+day_id);
    }
};

如何在下拉列表更改事件中调用 getPossibleExcursions(day_id) 函数?

它总是显示:

  

未捕获的ReferenceError:未定义getPossibleExcursions。

1 个答案:

答案 0 :(得分:1)

您必须为某些变量指定this以供将来参考。定义更改事件时,this引用要添加事件的DOM对象,而不是实际对象。因此,将this分配给某些变量,比如self,并在on change函数中重复使用它。

现在您可以使用self来引用对象,使用this来获取DOM对象



var TourItinerary = {  
    EXCURSIONS:{

    },
    init:function(){
        console.log('Initializing...');
        this.initializeElements();
    },       
    initializeElements:function(){
        console.log('init elements...');
        var self = this;
        $("select[id^='start_city_']").change(function(){
            var day_id = $(this).attr('id').replace("start_city_","");
            self.getPossibleExcursions(day_id);
            console.log("value = " + $(this).val());
        });
    },
    getPossibleExcursions: function(day_id){
        console.log('Day Id ='+day_id);
    }
};

$(document).ready(function(){
    TourItinerary.init();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="start_city_123">
   <option value="a">a</option>
   <option value="b">b</option>
   <option value="c">c</option>
   <option value="d">d</option>
   <option value="e">e</option>
</select>
&#13;
&#13;
&#13;