我有一张桌子.有些行是由jquery动态添加的.
<td>每行的第一行都有一个<input type="text" />元素.使用jQuery,是否可以检查所有这些输入元素是否具有唯一值?
您可以为此使用数组和jQuery .inArray 函数,如下所示:
var vals = new Array();
$("td:first-child input").each(function() {
if($.inArray($(this).val(), vals) == -1) { //Not found
vals.push($(this).val());
} else {
alert("Duplicate found: " + $(this).val());
}
});
Run Code Online (Sandbox Code Playgroud)
如果您要重用它,请务必在第二遍之前清除 vals。
Nick的解决方案具有O(n 2)复杂度.这是一个优化的例子.
功能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>
Run Code Online (Sandbox Code Playgroud)