简体   繁体   English

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

[英]Selectize.js delegated event on option not working

I'm currently trying to listen to click events on generated options inside the dropdown, but I'm currently unable to achieve this.我目前正在尝试收听下拉菜单中生成的选项的点击事件,但我目前无法实现这一点。

Since options aren't generated when the DOM loads, I'm delegating the event to the document listening for clicks on the dropdown's options.由于在加载 DOM 时不会生成选项,因此我将事件委托给文档以侦听下拉选项的点击。 My code currently looks like this:我的代码目前如下所示:

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

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

But this doesn't seem to be working.但这似乎不起作用。 Any idea on why this is happening?知道为什么会这样吗? Any clue regarding why this event isn't firing at all will be more than welcome.关于为什么这个事件根本没有触发的任何线索都将非常受欢迎。

Edit: Just an FYI, I'm adding a class to the HTML input element, that's why I'm listening for clicks on .accounts-input-selectize .option :编辑:仅供参考,我正在向 HTML 输入元素添加一个类,这就是为什么我正在监听.accounts-input-selectize .option

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

The question sounds simple, but its not. 这个问题听起来很简单,但事实并非如此。 The trouble is that selectize prevents all defaults, so at first I wouldn recommend using this lib, but still, if you really want to, there is a way to find out if user changed the option or not. 问题是selectize会阻止所有默认值,因此起初我不建议使用此lib,但是,如果您确实愿意,仍然可以找到一种方法来确定用户是否更改了该选项。

$('#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/ https://jsfiddle.net/mo1Ljm7r/13/

My approach to an admitedly half-baked "solution" is to create a plugin that intercepts the default event listener for clicks on options: 对于公认的半熟“解决方案”,我的方法是创建一个插件,该插件可拦截默认事件侦听器以实现对选项的点击:

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);
      }
    });
  }
});

The next step was to initialize Selectize using the previously created plugin, like this: 下一步是使用先前创建的插件初始化Selectize,如下所示:

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

And that's it. 就是这样。

basing this off NicolasJEngler's self-answer , I've made a microplugin that deselects the clicked-on option.基于NicolasJEngler 的自我回答,我制作了一个微插件,可以取消选择点击选项。 The issue I ran into is this event always gets triggered after an option is added, so you can't tell if it already existed when clicked on.我遇到的问题是这个事件总是在添加一个选项后被触发,所以当你点击它时你无法判断它是否已经存在。 Therefore, I add a class to the option element when clicked/unclicked to check if it's newly added or not.因此,我在单击/取消单击时向选项元素添加了一个类,以检查它是否是新添加的。

Hope it helps someone!希望它可以帮助某人!

/* Selectize deselect function */
Selectize.define('click2deselect', function(options) {
    var self = this;
    var setup = self.setup;
    this.setup = function() {
        setup.apply(self, arguments);
        // add additional handler
        self.$dropdown.on('mousedown click', '[data-selectable]', function(e) {
            let value = this.getAttribute('data-value');
            if( this.classList.contains('checked') ) {
                this.classList.remove('checked');
                self.removeItem(value);
                self.refreshItems();
                self.refreshOptions();
            }else{
                this.classList.add('checked');
            }
        });
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM