我目前正在尝试在下拉菜单中监听生成的选项上的点击事件,但目前无法实现。
由于加载DOM时不会生成选项,因此我将事件委派给了文档,以监听下拉菜单中的选项是否被点击。我的代码当前如下所示:
var $accountsSelectize = $('#accounts-input').selectize({
...
});
$(document).on('click', '.accounts-input-selectize .option', function(event) {
alert('An option was clicked!');
});
但这似乎不起作用。知道为什么会这样吗?关于此事件为何根本不触发的任何线索都将受到欢迎。
编辑:仅供参考,我向HTML输入元素添加了一个类,这就是为什么我要监听点击的原因.accounts-input-selectize .option
:
<input type="text" id="accounts-input" class="accounts-input-selectize" placeholder="Search accounts">
我认为是半生不熟的“解决方案”的方法是创建一个插件,该插件可拦截默认的事件侦听器,以实现对选项的点击:
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'],
...
});
就是这样。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句