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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:21:55  来源:igfitidea点击:

How to open the select input using jquery

javascriptjqueryselect

提问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 DIVor 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.");
}

Example

例子

回答by fabbb

Just an update here as the accepted answer is correct but outdated and initMouseEventis 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 downusing any code. But still you can change the selected option using the code. Pls see this

我认为您不能强制选择框drop down使用任何代码。但是您仍然可以使用代码更改所选选项。请看这个

http://www.mredkj.com/tutorials/tutorial003.html

http://www.mredkj.com/tutorials/tutorial003.html