Selectize.js委托事件选项不起作用

时间:2017-01-09 21:11:51

标签: javascript jquery events selectize.js

我目前正在尝试收听下拉列表中生成的选项的点击事件,但我目前无法实现此目的。

由于DOM加载时未生成选项,因此我将事件委托给文档,以监听下拉列表选项的点击次数。我的代码目前看起来像这样:

var $accountsSelectize = $('#accounts-input').selectize({
  ...
});

$(document).on('click', '.accounts-input-selectize .option', function(event) {
  alert('An option was clicked!');
});

但这似乎不起作用。对于为什么会发生这种情况的任何想法?关于为什么这个事件根本不会被解雇的任何线索都将非常受欢迎。

编辑:只是一个FYI,我在HTML输入元素中添加了一个类,这就是为什么我在听.accounts-input-selectize .option点击的原因:

<input type="text" id="accounts-input" class="accounts-input-selectize" placeholder="Search accounts">

2 个答案:

答案 0 :(得分:1)

这个问题听起来很简单,但事实并非如此。麻烦的是,选择会阻止所有默认值,所以一开始我不推荐使用这个库,但是,如果你真的想,还有一种方法可以找出用户是否更改了选项。

$('#select-country').selectize({

      //When user selects the widget we'll rememberize its value
      onFocus: function(){
        $(this).data('temp-saved', $('#select-country').val());
      },

      //On blur we check if the value has not changed
      onBlur: function(){
        var previous = $(this).data('temp-saved');
        var current = $('#select-country').val();

        if (current == previous) {
                console.log('NOT changed!');
        }
      },

      //And on change we sure that the value has changed
      onChange: function(current){
            var previous = $(this).data('temp-saved');
            console.log('changed from', previous, 'to', current);
      }
  });

https://jsfiddle.net/mo1Ljm7r/13/

答案 1 :(得分:1)

我对一个令人敬畏的半成品“解决方案”的方法是创建一个插件来拦截默认事件监听器以获取选项的点击:

Selectize.define('click2deselect', function(options) {
  var self = this;
  var setup = self.setup;
  this.setup = function() {
    setup.apply(self, arguments);

    // Intercept default handlers
    self.$dropdown.off('mousedown click', '[data-selectable]').on('mousedown click', '[data-selectable]', function(e) {
      var value = $(this).attr('data-value'),
          inputValue = self.$input.attr('value');

      if (inputValue.indexOf(value) !== -1) {
        var inputValueArray = inputValue.split(','),
            index = inputValueArray.indexOf(value);

        inputValueArray.splice(index, 1);

        self.setValue(inputValueArray);
        self.focus();
      } else {
        return self.onOptionSelect.apply(self, arguments);
      }
    });
  }
});

下一步是使用之前创建的插件初始化Selectize,如下所示:

var $accountsSelectize = $('#accounts-input').selectize({
  plugins: ['click2deselect'],
  ...
});

就是这样。