繁体   English   中英

使用jQuery在选择框中选择最接近的值

[英]Select closest value in select box with jquery

从API中我得到了“时间”,然后将“时间”放入选择框,例如:

<select id="time">
  <option value="19:00:00">19:00:00</option>
  <option value="20:00:00">20:00:00</option>
  <option value="21:00:00">21:00:00</option>
  <option value="22:00:00">22:00:00</option> /// ETC
</select>

我想显示20:00:00作为默认时间,所以我只需编写jquery代码:

$('#time').val('20:00:00');

问题是因为API不会在每次20:00:00时都返回我作为选项,所以我需要选择其他时间,因此如何使用jquery选择最接近20:00:00的时间,等等。如何选择21:00:00如果20:00:00不在选择框中?

您可以找到等于或大于所需时间的所有选项,然后选择第一个(前提是已订购该列表)。

 var time = '20:00:00'; function changeTime ( value ) { //select all the options and filter them $('#time option').filter(function(index, element){ //return just the ones that have a value equal to or //greater than our desired time return element.value >= value; }).eq(0).prop('selected', true); //select the first one } changeTime( time ); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="time"> <option value="19:00:00">19:00:00</option> <option value="21:00:00">21:00:00</option> <option value="22:00:00">22:00:00</option> /// ETC </select> 

暂无
暂无

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

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