javascript - 键盘按键和箭头无法正确使用此脚本

标签 javascript jquery

我有这个脚本,您可以输出您在选择标记中选择的值,这与单击事件完美配合,但如果我单击第一个输入并按选项卡按钮以移动到选择标记,而不需要使用

鼠标导航到选择标签,然后您可以使用键盘箭头或键入您在选择标签选项中看到的值来选择值,但它不起作用,或者它很少足以显示我的值' m 在 id 元素中输出调用numbersMessage,有时我

必须双重输入该值才能使其显示我在numbersMessage 元素中的值。那么我怎样才能让它与箭头键一起工作,当我输入我在选择标签中看到的内容时,这里就是我的代码。

 $(document).ready(function(){
   function nF(){
      var numberX = document.getElementById('numbers').value;
    
    if(numberX == 'one'){
       $('#numbersMessage').html('You selected: ' + numberX);
    }
    
    else if(numberX == 'two'){
       $('#numbersMessage').html('You selected: ' + numberX);
    }
    
     else if(numberX == 'three'){
       $('#numbersMessage').html('You selected: ' + numberX);
    }
   }
    
    //Works perfect, any click will output the value I selected
    $('#numbers').click(function(){
   nF();
  });
   
  //Not working how I wan't it to work...
  $('#numbers').keypress(function(){
   nF();
  });
    
});
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>

<p>Click on the first input and press the tab key on the keyboard and type out the select option value out or use the arrows on the keyboard to see what value you will select in the select tag a message should appear on what value you have selected below.</p>

<input style='display:block; width: 800px;'type='text'>

<select id='numbers'>
<option value='one'>1</option>
<option value='two'>2</option>
<option value='three'>3</option>
</select>

<p id='numbersMessage'></p>

最后一件事,输入元素在这个代码示例中并不重要,我只是添加了该输入元素来向你们展示选择标记脚本在哪些其他情况下无法正常工作,所以你们不会感到困惑为什么我要放入该输入标签。

最佳答案

$('#numbers').on('change', function(){
   nF();
});

尝试调用下拉列表的更改事件。

关于javascript - 键盘按键和箭头无法正确使用此脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50601435/

相关文章:

javascript - Zurb 插件 “twentytwenty” 可以在 Foundation 4 Reveal Modal 中运行吗?

javascript - 无法理解为什么 javascript 函数无法正确设置变量

javascript - 单击链接图像以关闭/隐藏 div

javascript - 通过 jQuery 加载图像

javascript - 使用css将标题分成jquery中的列

javascript - 代码可以在 Dreamweaver cs6 中运行,但不能在 chrome/firefox 中运行。?

javascript - EJS动态包含

javascript - 将 Isotope v2 与 RequireJS 结合使用

javascript - 如何在任何网络浏览器中运行 Puppeteer 代码?

jquery - 使用 JQuery 将两个输入框合并为一个