0
我正在尝试将自定义点击事件添加到我已经嵌入到select2处理程序中的图标。我没有使用默认的'x',而是添加了三个图形图标,我想将自定义点击处理程序附加到并使用select2事件API执行操作。jQuery select2无法将点击事件添加到自定义模板
它看起来像这样的作品,如果我点击实际的标签,但不是我喜欢的个别图标。
我的JavaScript看起来如下:
$(document).ready(function() {
function formatPattern(p)
{
if (!p.id) return p.text;
var html;
html = '<div class="action-group">';
html += '<a href="#" class="glyphicon glyphicon-remove"></a>';
html += '<a href="#" class="glyphicon glyphicon-play"></a>';
html += '<a href="#" class="glyphicon glyphicon-pause"></a>';
html += '</div>';
html += '<div class="select-text">' + p.id + '</div>';
return html;
}
var tagBox = $('#tagPicker');
tagBox.select2({
tags: ['A', 'B', 'C'],
closeOnSelect: false,
formatResult: formatPattern,
formatSelection: formatPattern,
escapeMarkup: function(m) { return m; }
});
tagBox = tagBox.data('select2');
tagBox.selectChoice = (function(fn) {
return function(data, options) {
var target;
console.log(data);
console.log(options);
if (options != null) {
target = $(options.target);
}
if (target && target.hasClass('glyphicon-play')) {
console.log(" clicked play button ");
} else {
return fn.apply(this, arguments);
}
}
})(tagBox.selectChoice);
});
这里的的jsfiddle:https://jsfiddle.net/Lwda44q5/
看起来不错,只是这个错误是,在添加新标签,单击事件处理程序并不重视它。我认为'on()'是为此而建的,但有些东西是关闭的。 – randombits
因为你需要声明处理程序:$(document).on(“click”,“。action-group a”,function(){});.这将注册任何创建的动态元素 – DinoMyte
绝对试图 - 试图找出为什么它不起作用。 – randombits