使用jQuery或javascript查找最接近的匹配值 [英] Finding Closest Matching Value using jQuery or javascript
本文介绍了使用jQuery或javascript查找最接近的匹配值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑一个标记,例如
<select id="blah">
<option value="3">Some text</option>
<option value="4">Some text</option>
<option value="8">Some text</option> // <---- target this tag based on value 7
<option value="19">Some text</option>
</select>
假设我有一个值,比如说7.是否可以定位其选项标签 value
属性最接近7,在这种情况下,它将是< option value =8>
?
Suppose I have a value with me, say 7. Is it possible to target the option tag whose value
attribute is closest to 7 which, in this case, would be <option value="8">
?
我知道 ^
这意味着从和 $ $ c开始$ c>这意味着结束并且希望是否有类似的东西来找到给定值的最接近的匹配。
I'm aware of ^
which means starting with and $
which means ending with and was hoping if there is something like this to find the closest match for a given value.
推荐答案
我会这样:
http:// jsfiddle .net / GNNHy /
var $tmpOption = $('<option value="7">Some text 7</option>');
$("#blah").append($tmpOption);
var my_options = $("#blah option");
my_options.sort(function(a,b) {
if (parseInt(a.value,10) > parseInt(b.value,10)) return 1;
else if (parseInt(a.value,10) < parseInt(b.value,10)) return -1;
else return 0
})
$("#blah").empty().append( my_options );
这篇关于使用jQuery或javascript查找最接近的匹配值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文