使用jquery,如何检查输入元素的集合是否具有唯一值? [英] Using jquery, how can I check that a collection of input elements have unique values?
本文介绍了使用jquery,如何检查输入元素的集合是否具有唯一值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一张桌子.某些行是由jquery动态添加的.
I have a table. Some rows are dynamically added by jquery.
每行的第一个<td>
都有一个<input type="text" />
元素.使用jQuery,是否可以检查所有这些输入元素是否具有唯一值?
The first <td>
of each row has an <input type="text" />
element. Using jQuery, is it possible to check that all these input elements have unique values?
推荐答案
Nick的解决方案具有O(n 2 )复杂度.这是一个优化的示例.
Nick's solution has O(n2) complexity. Here's an optimized example.
功能isUnique
确定所需的结果.
<script src="jquery.js" />
<script>
function isUnique( tableSelector ) {
// Collect all values in an array
var values = [] ;
$( tableSelector + ' td:first-child input[type="text"]' ).each( function(idx,val){ values.push($(val).val()); } );
// Sort it
values.sort() ;
// Check whether there are two equal values next to each other
for( var k = 1; k < values.length; ++k ) {
if( values[k] == values[k-1] ) return false ;
}
return true ;
}
// Test it
$(document).ready(function(){
alert( isUnique( ".myTable" ) ) ;
});
</script>
<table class="myTable">
<tr><td><input type="text" value="1" /></td></tr>
<tr><td><input type="text" value="2" /></td></tr>
</table>
这篇关于使用jquery,如何检查输入元素的集合是否具有唯一值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文