Javascript 如何使用jquery打开选择输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10453393/
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
How to open the select input using jquery
提问by Ali Bassam
So I can see the options of the select element but I need to click on it. What if I want to use a function? When something happens this select element should be selected, means the list is open and I can see the options. I don't want the user to click on the select element, I want something else to open it.
所以我可以看到选择元素的选项,但我需要点击它。如果我想使用一个函数怎么办?当发生某些事情时,应该选择这个 select 元素,这意味着列表是打开的,我可以看到选项。我不希望用户点击选择元素,我想要其他东西来打开它。
What I've tried
我试过的
$("select").select();
$("select").click();
$("select").focus();
There is a select element, usually if you want it to open (the drop down list), you click on it. What I want is to open it if I click on a DIV
or anything else. I want this drop down list to to open, without having the user clicking on the select element.
有一个选择元素,通常如果你想打开它(下拉列表),你点击它。我想要的是打开它,如果我点击 aDIV
或其他任何东西。我希望打开此下拉列表,而无需用户单击选择元素。
回答by noob
This should work:
这应该有效:
var element = $("select")[0], worked = false;
if (document.createEvent) { // all browsers
var e = document.createEvent("MouseEvents");
e.initMouseEvent("mousedown", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
worked = element.dispatchEvent(e);
} else if (element.fireEvent) { // ie
worked = element.fireEvent("onmousedown");
}
if (!worked) { // unknown browser / error
alert("It didn't worked in your browser.");
}
回答by fabbb
Just an update here as the accepted answer is correct but outdated and initMouseEvent
is soon to be deprecated. [See: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/initMouseEvent]
只是在这里更新,因为接受的答案是正确的,但已经过时,initMouseEvent
很快就会被弃用。[参见:https: //developer.mozilla.org/en-US/docs/Web/API/MouseEvent/initMouseEvent]
Use the following instead: new MouseEvent
[See: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent]
请改用以下内容:new MouseEvent
[参见:https: //developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent]
Example code:
示例代码:
var el = $('select'); // grab the input (jQuery)
var event = new MouseEvent('mousedown'); // create the event listener
el.dispatchEvent(event); // attach the event listener to the element
回答by Nauphal
I dont think you can force the select box to drop down
using any code. But still you can change the selected option using the code. Pls see this
我认为您不能强制选择框drop down
使用任何代码。但是您仍然可以使用代码更改所选选项。请看这个