使用jquery,我如何检查输入元素的集合是否具有唯一值?

lov*_*iji 7 jquery

我有一张桌子.有些行是由jquery动态添加的.

<td>每行的第一行都有一个<input type="text" />元素.使用jQuery,是否可以检查所有这些输入元素是否具有唯一值?

Nic*_*ver 7

您可以为此使用数组和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。


St.*_*and 6

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)

  • 这个循环遍历数组 3 次加上排序……性能差异需要十万次循环才能达到 1 毫秒,在这种情况下,所有时间都花在选择器上。对于这样的事情,我将在一周中的任何一天采用比 0.000001ms 的执行时间改进更直接的代码:) (2认同)