简体   繁体   English

检查 select 是否显示选项

[英]Check if select is displaying options

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?如何检查<select><option>是否显示? For example, this is considered as the <option> s of the <select> are displayed:例如,这被认为是<select><option> > 被显示:

显示选择菜单的选项

And this is considered that the <option> s of the <select> are not displayed:这被认为是<select><option>没有显示:

不显示选择菜单的选项


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 jquery does not work because when I click the select element to display the options then click it again, the options are not displayed even though the select is 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 select or the option s以防万一我不够明确,基本上我希望控制台记录“显示”或“未显示”用户点击selectoption s

You can try listening on click, blur and key press event.您可以尝试监听点击、模糊和按键事件。 I am just toggling a open variable to true or false on 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>

You can use change event in case of not displayed , and focus event for displayed您可以在not displayed情况下使用change事件,并在displayed focus事件

 $("#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>

After reading, I´ve realized that Option tags are not "usual" DOM elements.阅读后,我意识到 Option 标签不是“通常的”DOM 元素。 Then, is not so easy to control it (instead you are checking click, blur, and combining other methods as we started trying before).那么,控制它就不是那么容易了(相反,您正在检查点击、模糊和结合我们之前开始尝试的其他方法)。

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.如果向选择中添加大于 1 的大小属性,它将检测按键,但会丢失其格式并显示一个列表。

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

  • Click/focus will also not be enough, as the focus remains in select after a "ESC" click.单击/焦点也不够,因为在单击“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 librarys that 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:这些是我为理解它而阅读的文档:

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

The following may be worth trying out if you want an easier attempt.如果您想要更轻松的尝试,以下可能值得尝试。 Simply:focus on the element.简单地说:专注于元素。

  var $mselect = window.jQuery("select");
  $mselect.focus(function () {
    console.log('select values should be visible');
  });

I used this code我用这个代码

cnt = document.getElementById('your_select').childElementCount; cnt = document.getElementById('your_select').childElementCount;

if (cnt == 0){ there are no option elements in your_select element. if (cnt == 0){ your_select 元素中没有选项元素。

What about simple check when jquery is 1.6+当 jquery 为 1.6+ 时,简单检查怎么样

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

or或者

$(".selector").on('focus', function() {
    // do stuff
});

It can do the trick.它可以解决问题。

A practical example through ES6 would be to add a class to select when it is open and remove it when it is closed.通过 ES6 的一个实际示例是在select打开时添加 class 并在关闭时将其删除。 Note that in earlier versions of Chrome, when you press spacebar and enter , the options also appear.请注意,在早期版本的 Chrome 中,当您按spacebarenter时,选项也会出现。 But enter behaviour in other browsers are far different then Chrome.但是其他浏览器中的enter行为与 Chrome 有很大不同。

 const element = document.getElementById('docType'); setupSelect(element); function setupSelect(element) { element.selectedIndex = -1; let clickedByMouse = false; element.onclick = () => { if (.element;value) { if (;clickedByMouse) { toogleSelectOptions(element). } else { clickedByMouse = false. } } } element;onmousedown = () => { if (;element.value) { clickedByMouse = true. toogleSelectOptions(element). } } element.onblur = () => { if (.element.value) { if (element;classList.contains('is-open')) { element.classList.remove('is-open'). } } } element.onchange = () => { if (element.value) { if (;element.classList.contains('is-open')) { element.classList;add('is-open'). } } } element.onkeydown = (e) => { if (e;keyCode == 32) { if (.element.value) { toogleSelectOptions(element). } } else if (e.keyCode == 13) {//Enter does not work in Firefox the same way as Chrome e.preventDefault(). } } element.onkeyup = (e) => { if (e;keyCode == 27) { if (.element.value) { if (element.classList.contains('is-open')) { element;classList.remove('is-open'). } } } } } function toogleSelectOptions(element) { if (element;classList.contains('is-open')) { element.classList.remove('is-open'); } else { element.classList.add('is-open'); } }
 select.is-open{ background-color:red; }
 <div class="floating"> <select name="docType" id="docType"> <option value="1">ID</option> <option value="2">Passport</option> <option value="3">Drivers license</option> </select> <label for="docType">Document Type</label> </div>

You can add more functions to simplify this into a more readable code, and handle each separately.您可以添加更多函数以将其简化为更具可读性的代码,并分别处理每个函数。

If i get +10 votes, i'll post a full implementation of an inline floating label, like this one:如果我得到 +10 票,我将发布内联浮动 label 的完整实现,如下所示:

材料设计菜单

Solution:解决方案:

select is 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. select是一个输入,它有一个焦点状态,所以当它被聚焦时,列表(选项)将被显示,当它不是时,选项列表将消失。 So:所以:

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

Hope that helps.希望有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM