单击选择框上的触发器在 jQuery 中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2895608/
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
Click trigger on select box doesn't work in jQuery
提问by sasa
How can a dropdown list can be opened with a trigger?
如何使用触发器打开下拉列表?
Here is the code which doesn't work:
这是不起作用的代码:
$('select').trigger('click');
Just for note - mousedown and mouseup also doesn't work.
仅供参考 - mousedown 和 mouseup 也不起作用。
回答by Renso
$('select').children('option').each(function() {
if ($(this).is(':selected'))
{ $(this).trigger('change'); }
});
回答by Darin Dimitrov
What you are trying to achieve is impossible. Even if you trigger a clickthe drop down list won't open like if the user clicked on it. If you want to change the currently selected value with a new one you could use the valfunction. I guess the only solution is to simulate the whole UI look and feel of a select
element using divs.
你想要达到的目标是不可能的。即使您触发了点击,下拉列表也不会像用户点击它那样打开。如果你想用一个新的值改变当前选择的值,你可以使用val函数。我想唯一的解决方案是select
使用 div模拟元素的整个 UI 外观和感觉。
回答by Jonathan
Took me a while but found a solution:
花了我一段时间,但找到了解决方案:
(Chrome & Safari ONLY)
(仅限 Chrome 和 Safari)
function open(elem) {
if (document.createEvent) {
var e = document.createEvent("MouseEvents");
e.initMouseEvent("mousedown", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
elem[0].dispatchEvent(e);
} else if (element.fireEvent) {
elem[0].fireEvent("onmousedown");
}
}
回答by izocan
There is no proper way to click on a dropdown programmatically.
没有以编程方式单击下拉列表的正确方法。
You can either select an option via:
您可以通过以下方式选择一个选项:
$('#sourceOptions>option:eq(0)').prop('selected', 'selected');
If you want to simulate a user click: you have to do it as @Renso says it:
如果你想模拟用户点击:你必须像@Renso 所说的那样做:
$('#sourceOptions>option:eq(0)').prop('selected', 'selected').trigger('change');