首页 > 解决方案 > 使用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 不在选择框中?

标签: javascriptjqueryhtmlselect

解决方案


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

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>


推荐阅读