我如何在 selectize 的 onChange 中调用函数?

How can i call a function inside onChange of selectize?

如何在 selectize 的 onChange 中调用函数?

onChange: function(value){
  weatherWidget(value)
}

$(document).ready(function() {
  function weatherWidget(location){
    console.log('test');
  }
}

这段代码给了我未定义的函数。谢谢

您遇到范围问题。您也可以将 selectize 调用包装在 $(document).ready 中(无论如何都应该将其包装在其中),或者将您的函数声明留在它之外,因为它将在解析时加载。我建议将函数保留在 $(document).ready 之外,如下所示:

$(document).ready(function() {
  $(x).selectize({
    ....
    },
    onChange: function(value) {
      weatherWidget(value);
    }
  });    
});

function weatherWidget(location) {
  console.log(location);
}

这是在选择下拉列表中触发值更改的方法:

       $('#selector').selectize({
            onInitialize: function() {
                this.trigger('change', this.getValue(), true);
            },
            onChange: function(value, isOnInitialize) {
                if(value !== ''){
                   alert('Value has been changed: ' + value);
                }
                
            }
        });