javascript 将点击事件附加到 .select2-result 中的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15636302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Attach click-event to element in .select2-result
提问by brckmann
I'm looking for a way to attach a click-event to a select2-result-item. I've gone ahead and formatted both result and selection via
我正在寻找一种将点击事件附加到 select2-result-item 的方法。我已经通过以下方式格式化了结果和选择
function format(state) {
if (!state.id) return state.text; // optgroup
return state.text + " <i class='info'>link</i>";
}
to add an "info"-icon I'm now trying to attach a simple click-event to the .info-element but can't get this to work:
添加一个“信息”图标我现在试图将一个简单的点击事件附加到 .info-element 但无法让它工作:
$('.info').on('click', function(event){
event.preventDefault();
alert("CLICK");
$('#log').text( "clicked" );
});
Any help? Anyone with a similar problem? Is this possible at all?
有什么帮助吗?有类似问题的人吗?这可能吗?
I prepared a jsFiddle at: http://jsfiddle.net/s2dqh/3/
我在以下位置准备了一个 jsFiddle:http: //jsfiddle.net/s2dqh/3/
回答by ant_Ti
Because Select2 lib prevent any click events on popover list you can't bind events to .info
directly. But you can redefine onSelect
method and place there any code you want.
因为 Select2 lib 阻止了弹出列表上的任何点击事件,所以您不能.info
直接将事件绑定到。但是您可以重新定义onSelect
方法并在其中放置您想要的任何代码。
See example: http://jsfiddle.net/f8q2by55/
参见示例:http: //jsfiddle.net/f8q2by55/
Update for multiple selects: http://jsfiddle.net/6jaodjzq/
多选更新:http: //jsfiddle.net/6jaodjzq/
回答by AaronLS
This is similar in concept to netme's but the select2 event is wrong(maybe version difference), and you need to use stopPropagation to prevent item from being selected:
这与netme的概念相似,但select2事件错误(可能是版本差异),您需要使用stopPropagation来防止项目被选中:
$('#mySelect2').on('select2-open', function() {
$('.select2-results .info').on('mouseup', function(e) {
e.stopPropagation();
console.log('clicked');
});
});
If used with x-editable. What this does is when the x-editable goes into edit mode(shown event), that's when a select2 exists and you can wire to it's open function.
如果与 x-editable 一起使用。这是当 x-editable 进入编辑模式(显示的事件)时,即存在 select2 并且您可以连接到它的打开功能时。
$('#myXEditable').on('shown', function () {
$(this).data('editable').input.$input.on('select2-open', function() {
$('.select2-results .info').on('mouseup', function(e) {
e.stopPropagation();
console.log('clicked');
});
});
});
回答by Kevin Brown
For versions of Select2 before 4.0.0 (so 3.5.x and below), you should refer to this answer about binding to onSelect
.
对于 4.0.0 之前的 Select2 版本(因此是 3.5.x 及以下),您应该参考有关绑定到onSelect
.
In newer versions of Select2, events are no longer killed within the results so you can just bind to the mouseup
/mousedown
eventslike you normally would. You should avoid binding to the click
eventbecause by default browsers will not trigger it.
在较新版本的 Select2 中,事件不再在结果中被杀死,因此您可以mouseup
mousedown
像往常一样绑定到/事件。您应该避免绑定到该click
事件,因为默认浏览器不会触发它。
$(".select2").select2({
templateResult: function (data) {
if (data.id == null) {
return data.text;
}
var $option = $("<spam></span>");
var $preview = $("<a target='_blank'> (preview)</a>");
$preview.prop("href", data.id);
$preview.on('mouseup', function (evt) {
// Select2 will remove the dropdown on `mouseup`, which will prevent any `click` events from being triggered
// So we need to block the propagation of the `mouseup` event
evt.stopPropagation();
});
$preview.on('click', function (evt) {
console.log('the link was clicked');
});
$option.text(data.text);
$option.append($preview);
return $option;
}
});
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.js"></script>
<select class="select2" style="width: 200px;">
<option value="https://google.com">Google</option>
<option value="https://mail.google.com">GMail</option>
</select>
In this example we stop the propagation of the mouseup
event so the browser will trigger the click
event. If you are not working with actual links, but instead need to just catch a click
event, you should just hook into the mouseup
event.
在这个例子中,我们停止mouseup
事件的传播,以便浏览器触发click
事件。如果您不使用实际链接,而只需要捕获一个click
事件,您应该只钩入该mouseup
事件。
回答by kushalvm
A simpler approach according to docs.
根据文档的更简单的方法。
$('#mySelect2').on('select2:select', function (e) {
var data = e.params.data;
console.log(data);
});
Surprised not to see any answer for this.
很惊讶没有看到任何答案。
回答by Aegix
None of the answers above worked for me for select2 4.0.0, so here's what I ended up doing:
对于 select2 4.0.0,上面的答案都不适合我,所以这就是我最终要做的:
$(document).on('mouseup', '.select2-container--open .select2-results__option', function (e) {
// Act on the element
}
Specifically, I wanted to only act on the previously-selected item:
具体来说,我只想对先前选择的项目采取行动:
$(document).on('mouseup', '.select2-container--open .select2-results__option[aria-selected=true]', function (e) {
// Do something on the previously-selected item
}
回答by Balakrishnan Bsk
use default select2select event trigger instead of using other jquery events
使用默认的 select2select 事件触发器而不是使用其他 jquery 事件
$('#mySelect2').on('select2:select', function (e) {
var data = e.params.data;
console.log(data);
});
for more details refer below link https://select2.org/programmatic-control/events
有关更多详细信息,请参阅以下链接 https://select2.org/programmatic-control/events
回答by Mikhail Chernykh
Just add 'open' listener and set up another 'mouseup' listener for the '' tag:
只需添加 'open' 监听器并为 '' 标签设置另一个 'mouseup' 监听器:
$("#select").on('open', function() {
$('.select2-results i').on('mouseup', function() {
alert('aaa');
});
});
Here is the link to my solution: http://jsfiddle.net/EW8t7/
这是我的解决方案的链接:http: //jsfiddle.net/EW8t7/
回答by John S
I think Select2's handling of the mouseup event prevents the .info
element from getting a click event. Having the .info
element capture the mouseup event and prevent it from propagating seems to fix that.
我认为 Select2 对 mouseup 事件的处理阻止了.info
元素获得点击事件。让.info
元素捕获 mouseup 事件并阻止它传播似乎可以解决这个问题。
function format(state, container) {
if (!state.id) return state.text; // optgroup
container.append(state.text);
$('<i class="info">link</i>')
.appendTo(container)
.mouseup(function(e) {
e.stopPropagation();
})
.click(function(e) {
e.preventDefault();
alert('CLICK');
});
}
This can also be done to support a link in the selected item, but there it is the mousedown event that needs to be captured.
也可以这样做以支持所选项目中的链接,但需要捕获 mousedown 事件。
回答by divups
You need to unbind the mouseup event from the .select2-results__options element. I'm doing it in my templateResult function:
您需要从 .select2-results__options 元素解除 mouseup 事件的绑定。我在我的 templateResult 函数中这样做:
function templateResult(location) {
var $location = $([html with links]);
$('.select2-results__options').unbind('mouseup');
return $location;
}
If you want to keep select2's default behavior of selecting the option and closing the dropdown, you'll need manually trigger those events:
如果您想保留 select2 选择选项和关闭下拉列表的默认行为,您需要手动触发这些事件:
$('.select2-results__options').unbind('mouseup');
$('a', $location).on('click', function (e) {
$('#locations_dropdown').select2('val', location.id);
$('#locations_dropdown').select2('close');
});
return $location;
回答by Christian
the thing seems to be that the tgas will be deleted right after the box is closed. Therefore the click event cannot be fired.
事情似乎是在盒子关闭后将立即删除 tgas。因此无法触发 click 事件。
I've changed a few things + the event that will be listened on. It's now a mousedown...
我改变了一些事情+将被监听的事件。现在是鼠标按下...
function format(state) {
if (!state.id) return state.text; // optgroup
return state.text + " <a class='info'>link</a>";
}
$("select").select2({
formatResult: format,
formatSelection: format,
escapeMarkup: function(m) { return m; }
}).on('select2-open',function(){
console.log($('.info'))
$('.info').on('mousedown', function(event){
console.log("click")
$('#log').text( "clicked" );
event.preventDefault();
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.js"></script>
<select>
<option>red</option>
<option>green</option>
<option>blue</option>
</select>
<div id="log"></div>