簡體   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