Javascript 检查 select 是否显示选项

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

Check if select is displaying options

javascriptjqueryhtml

提问by chris97ong

I have the following HTML code:

我有以下 HTML 代码:

<select>
<option selected>Test 1</option>
<option>Test 2</option>
<option>Test 3</option>
</select>

How do I check if the <option>s of the <select>are displayed? For example, this is considered as the <option>s of the <select>are displayed:

如何检查 的<option>s<select>是否显示?例如,这被视为显示的<option>s <select>

Options of the select menu are displayed

显示选择菜单的选项

And this is considered that the <option>s of the <select>are not displayed:

这被认为是不显示的<option>s <select>

Options of the select menu are not displayed

不显示选择菜单的选项



I have tried this:

我试过这个:

$("#myselect").on("click", function() {
    if ($("#myselect option").length == 0) {
        console.log("not displayed");
    } else {
        console.log("displayed");
    } 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="myselect">
<option selected>Test 1</option>
<option>Test 2</option>
<option>Test 3</option>
</select>

But the console logs "displayed" all the time.

但是控制台日志一直“显示”。



So how can I achieve this?

那么我怎样才能做到这一点呢?



EDIT 1:

编辑 1:

The answers at How to check if an select element is still “open” / active with jquerydoes not work because when I click the selectelement to display the options then click it again, the options are not displayed even though the selectis still focused.

How to check if an select element is still “open” / active with jquery的答案不起作用,因为当我单击select元素以显示选项然后再次单击它时,即使select仍然聚焦,选项也不会显示。



EDIT 2:

编辑2:

Just in case I wasn't explicit enough, basically I want the console to log "displayed" or "not displayed" the user clicks on the selector the options

以防万一我不够明确,基本上我希望控制台记录“显示”或“未显示”用户点击selectoptions

采纳答案by Sami

You can try listening on click, blur and key press event. I am just toggling a openvariable to true or falseon each of the event.

您可以尝试监听点击、模糊和按键事件。我只是在每个事件上切换一个open变量true or false

   // if menu is open then true, if closed then false
   // we start with false
   var open = false;
   // just a function to print out message
   function isOpen(){
       if(open)
          return "menu is open";
       else
          return "menu is closed";
   }
   // on each click toggle the "open" variable
   $("#myselect").on("click", function() {
         open = !open;
         console.log(isOpen());
   });
   // on each blur toggle the "open" variable
   // fire only if menu is already in "open" state
   $("#myselect").on("blur", function() {
         if(open){
            open = !open;
            console.log(isOpen());
         }
   });
   // on ESC key toggle the "open" variable only if menu is in "open" state
   $(document).keyup(function(e) {
       if (e.keyCode == 27) { 
         if(open){
            open = !open;
            console.log(isOpen());
         }
       }
   });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="myselect">
<option selected>Test 1</option>
<option>Test 2</option>
<option>Test 3</option>
</select>

回答by Pranav C Balan

You can use changeevent in case of not displayed, and focusevent for displayed

您可以change在 的情况下使用事件not displayed,并将focus事件用于displayed

$("#myselect").on({
  "change": function() {
    $(this).blur();
  },
  'focus': function() {
    console.log("displayed");
  },
  "blur": function() {
    console.log("not displayed");
  },
  "keyup": function(e) {
    if (e.keyCode == 27)
      console.log("displayed");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="myselect">
  <option selected>Test 1</option>
  <option>Test 2</option>
  <option>Test 3</option>
</select>

回答by Alejandro Teixeira Mu?oz

After reading, I′ve realized that Option tags are not "usual" DOM elements. Then, is not so easy to control it (instead you are checking click, blur, and combining other methods as we started trying before).

读完之后,我意识到 Option 标签并不是“常见的”DOM 元素。那么,控制它就不是那么容易了(相反,您正在检查点击、模糊和结合我们之前开始尝试的其他方法)。

Now I′ve managed you finally found the solution in a mix of the first idea we had, then, i′ll just explain the other possible solutions you have and all the things I′ve learned about selects:

现在我已经设法让你终于找到了混合我们第一个想法的解决方案,然后,我将解释你拥有的其他可能的解决方案以及我学到的关于选择的所有内容:

  • If you DON′t add a size attribute to the select, you will not be able to detect keypress at the time it′s open.

  • If you add a size attribute bigger than 1 to the select, it will detect keypress, but will loose it′s format and a list will appear.

  • If you try to use offset, and similar, to check wether the select is open, is also not working, as the option objects do not have offset functions... (they are not usuarl DOM objects)

  • Click/focus will also not be enough, as the focus remains in select after a "ESC" click.

  • 如果你不给选择添加尺寸属性,你将无法在它打开时检测到按键。

  • 如果你在选择中添加一个大于 1 的 size 属性,它会检测按键,但会丢失它的格式并会出现一个列表。

  • 如果您尝试使用偏移量,类似地,检查选择是否打开,也不起作用,因为选项对象没有偏移功能......(它们不是通常的 DOM 对象)

  • 单击/聚焦也不够,因为在单击“ESC”后焦点仍处于选择状态。

Then, after all those things reviewed, I think it′s not possible to make it in a pure HTML way without doing a lot of click/blur controls like answered before.

然后,在完所有这些事情之后,我认为如果没有像之前回答的那样做很多点击/模糊控制,就不可能以纯 HTML 方式制作它。

Anyway, to clarify, there are lots of jquery librarysthat will help you to simulate a select/option dropdown, and to control if it′s open.

无论如何,澄清一下,有很多jquery 库可以帮助您模拟选择/选项下拉列表,并控制它是否打开。

I hope this answer will solve your Question. Check this functional fiddle I′ve prepared for you to show the jquery dropdown way:

我希望这个答案能解决你的问题。检查我为您准备的功能小提琴,以显示 jquery 下拉方式:

$('#jq-dropdown-1').on('show', function(event, dropdownData) {
  console.log("SHOWN");
}).on('hide', function(event, dropdownData) {
  console.log("HIDDEN");
});
<link rel="stylesheet" href="https://rawgit.com/claviska/jquery-dropdown/master/jquery.dropdown.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://rawgit.com/claviska/jquery-dropdown/master/jquery.dropdown.min.js"></script>

<a href="#" data-jq-dropdown="#jq-dropdown-1">dropdown</a>
<div id="jq-dropdown-1" class="jq-dropdown jq-dropdown-tip">
  <ul class="jq-dropdown-menu">
    <li><a href="#1">Item 1</a>
    </li>
    <li><a href="#2">Item 2</a>
    </li>
    <li><a href="#3">Item 3</a>
    </li>
    <li class="jq-dropdown-divider"></li>
    <li><a href="#4">Item 4</a>
    </li>
    <li><a href="#5">Item 5</a>
    </li>
    <li><a href="#5">Item 6</a>
    </li>
  </ul>
</div>


<button id="clickme">click me</button>

Those are the docs I′ve read to understand it:

这些是我为理解它而阅读的文档:

回答by Shafeeque

Im suggesting you to use new jquery selectmenu which is providing selectmenu open event

我建议您使用提供 selectmenu 打开事件的新 jquery selectmenu

$("#myselect").selectmenu({
  open: function(event, ui) {
    alert("opened");
  }
});
label {
  display: block;
}
select {
  width: 200px;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<select id="myselect">
  <option selected>Test 1</option>
  <option>Test 2</option>
  <option>Test 3</option>
</select>

Ref : http://api.jqueryui.com/selectmenu/#event-open

参考:http: //api.jqueryui.com/selectmenu/#event-open

回答by Eryk Wróbel

What about simple check when jquery is 1.6+

当 jquery 为 1.6+ 时,简单检查怎么样

  if ($(".selector").is(":focus")){
      // do stuff
  }

It can do the trick.

它可以解决问题。

回答by Fadi Obaji

Solution:

解决方案:

selectis an input, it has a focus state, so when it's focused the list(options) will be displayed, when it's not the list of options will disappear. So:

select是一个输入,它有一个焦点状态,所以当它被聚焦时,列表(选项)将被显示,当它不是时,选项列表将消失。所以:

$("#myselect").on("click", function() {
    if ($("#mySelect").is(":focus")) {
        console.log("displayed");
    } else {
        console.log("not displayed");
    } 
});

Hope that helps.

希望有帮助。