javascript - 使用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>
推荐阅读
- opencv - 如何使用 contrib 模块构建 OpenCV?
- php - 如何提取段落标签之间的链接
- python - python 扩展在 Microsoft Visual Studio Community 2019 中不可用?
- linux - 在 docker 上使用最新的 curl 版本
- image - 家长告诉孩子,孩子可以下载图片
- ruby-on-rails - 在控制器的模型中访问助手
- woocommerce - 限制woocommerce类别描述
- arrays - 如何在一个数组中推送多个图像?
- vue.js - 如何将服务工作者添加到 Vue.js 项目?
- c++ - 无法在分配 flex/bison 中将 'char*' 转换为 'float'