Javascript 在 jQuery 中显示选择下拉列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4457076/
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-23 12:28:48  来源:igfitidea点击:

Show select dropdown in jQuery?

javascriptjqueryselectdrop-down-menu

提问by Hailwood

Possible Duplicate:
How can you programmatically tell an HTML SELECT to drop down (for example, due to mouseover)?

可能的重复:
如何以编程方式告诉 HTML SELECT 下拉(例如,由于鼠标悬停)?

Is it possible to make the dropdown on a select element visible with jQuery?

是否可以使用jQuery使选择元素上的下拉列表可见?

I tried using $('#dropdown').click();, but it has no effect.

我尝试使用$('#dropdown').click();,但没有效果。

回答by Stuck

This is not possible. You can only implement your own select-box, but this is bad for usability.

这不可能。您只能实现自己的选择框,但这不利于可用性。

another approach is to programmatically change the size-attribute of the select-box, but this is not really what you wanted.

另一种方法是以编程方式更改选择框的大小属性,但这并不是您真正想要的。

I suggest to think of why you need this and if there would be a nicer software-pattern?

我建议想想你为什么需要这个,以及是否会有更好的软件模式?

回答by Jonathon Bolster

No - you are unable to do this. It's roughly along the same lines of a button in it's pressed state when a user clicks it - an 'interim' operation for the user to set a value. You could focusto it, but that's about it.

不 - 你不能这样做。当用户单击按钮时,它与处于按下状态的按钮大致相同——这是用户设置值的“临时”操作。你可以focus,但仅此而已。

If you reallywanted to simulate this, you could play with some CSS. For example, you could create a list that lookslike the dropdown list and set the dropdown value based on whatever the user clicks - similar to how an autocomplete list looks.

如果你真的想模拟这个,你可以玩一些 CSS。例如,您可以创建一个看起来像下拉列表的列表,并根据用户单击的内容设置下拉值 - 类似于自动完成列表的外观。

You could always change it to a multiple line list box if you wanted to display all the values to the user. You'd do this by setting the sizeto any value and back to 1 when you want to hide. It's not perfect, but it's another option:

如果您想向用户显示所有值,您始终可以将其更改为多行列表框。您可以通过将 设置size为任何值并在想要隐藏时返回 1 来实现。它并不完美,但它是另一种选择:

$("#open").click(function(e){
   e.preventDefault();
   $("#myselect").attr("size",5);    
});

$("#myselect").click(function(){
   $(this).attr("size",1); 
});

http://jsfiddle.net/jonathon/cr25U/

http://jsfiddle.net/jonathon/cr25U/

回答by sje397

Here's my adaption:

这是我的改编:

HTML

HTML

<button id='btn'>Click Me</button>
<select id='test'>
    <option>Blah 1</option>
    <option>Blah 2</option>
    <option>Blah 3</option>
    <option>Blah 4</option>
</select>

JavaScript

JavaScript

$('#btn').click(function(){
    $('#test').attr('size', 5);
});

$('#test').change(function() {
   $(this).attr('size', 1); 
});

This doesn't open the drop list, but it kind of works.

这不会打开下拉列表,但它有点工作。

Demo here.

演示在这里