Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

javascript - Check if select is displaying options

I have the following HTML code:

<select>
<option selected>Test 1</option>
<option>Test 2</option>
<option>Test 3</option>
</select>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

   // 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...