Javascript Selectize.js delegated event on选项不起作用
我目前正在尝试在下拉列表中收听生成选项上的单击事件,但我目前无法实现这一点 由于DOM加载时不会生成选项,因此我将事件委托给文档,以侦听对下拉菜单选项的单击。我的代码当前如下所示:Javascript Selectize.js delegated event on选项不起作用,javascript,jquery,events,selectize.js,Javascript,Jquery,Events,Selectize.js,我目前正在尝试在下拉列表中收听生成选项上的单击事件,但我目前无法实现这一点 由于DOM加载时不会生成选项,因此我将事件委托给文档,以侦听对下拉菜单选项的单击。我的代码当前如下所示: var $accountsSelectize = $('#accounts-input').selectize({ ... }); $(document).on('click', '.accounts-input-selectize .option', function(event) { alert('An
var $accountsSelectize = $('#accounts-input').selectize({
...
});
$(document).on('click', '.accounts-input-selectize .option', function(event) {
alert('An option was clicked!');
});
var $accountsSelectize = $('#accounts-input').selectize({
plugins: ['click2deselect'],
...
});
但这似乎不起作用。你知道为什么会这样吗?任何关于这一事件为何根本没有发生的线索都将非常受欢迎
编辑:仅供参考,我正在向HTML输入元素添加一个类,这就是为什么我正在侦听对的单击。accounts input selectize。option
:
<input type="text" id="accounts-input" class="accounts-input-selectize" placeholder="Search accounts">
这个问题听起来很简单,但其实不是。问题是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);
}
});
对于一个令人钦佩的半生不熟的“解决方案”,我的方法是创建一个插件,拦截默认事件监听器以点击选项:
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({
...
});
$(document).on('click', '.accounts-input-selectize .option', function(event) {
alert('An option was clicked!');
});
var $accountsSelectize = $('#accounts-input').selectize({
plugins: ['click2deselect'],
...
});
就是这样。selectize中没有API
change
事件吗?为什么需要单击事件?有一个APIchange
事件,但如果我单击已选择的选项,它不会触发,这就是为什么我需要单击事件来检查该选项之前是否已选择。感谢您的帮助,我投票支持此事件,因为它可能对其他人有用,但这种方法对我不起作用,因为我需要检查单击是否有已选择的值(模糊或聚焦可能适用于其他情况),但单击已选择的选项时不会触发这些事件。我将在一分钟内发布我的解决方案。用大炮射击鸟类)但这是唯一对我的案例有效的解决方案。如果提出了另一个更简单的解决方案,我将非常乐意接受它作为一个答案?