我有两个表 Table1 和 Table2。
每个表包含 <select>
标记和选项及其值相同。
现在我想检查每个表,有任何选项存在超过一次。如果是,则已选择警报选项。
我的代码是:
$('#table1 tr').each(function() {
$(this).find('select').change(function() { //alert($(this).val())
if ($('option[value=' + $(this).val() + ']:selected').length > 1) {
alert('option is already selected');
$(this).val($(this).find("option:first").val());
}
});
});
$('#table2 tr').each(function() {
$(this).find('select').change(function() { //alert($(this).val())
if ($('option[value=' + $(this).val() + ']:selected').length > 1) {
alert('option is already selected');
$(this).val($(this).find("option:first").val());
}
});
});
当在第一个表和第二个表中选择相同时,它将警告选项已被选择。我的代码有什么问题?
可以测试代码here .
最佳答案
问题是您选择了所有选项(表 1 + 2),而您应该选择了属于当前表的选项,如下所示。
$('#table1 tr').each(function() {
$(this).find('select').change(function(){//alert($(this).val())
if( $('#table1').find('select option[value='+$(this).val()+']:selected').length>1){
alert('option is already selected');
$(this).val($(this).find("option:first").val());
}
});
});
$('#table2 tr').each(function() {
$(this).find('select').change(function(){//alert($(this).val())
if($('#table2').find('select option[value='+$(this).val()+']:selected').length>1){
alert('option is already selected');
$(this).val($(this).find("option:first").val());
}
});
});
演示@ Fiddle
编辑:
稍微好一点的版本:
// Have a class if you will, for your 2 tables (or more) which would avoid the use of ID's as you may not even need them
// <table class="grouped-select" ... >
// and then do:
// $('.grouped-select').find('select').on('change', function() {
// or just use tag selector
$('table').find('select').on('change', function() {
//Cache jQuery references that you'd reuse over and over
var $this = $(this);
if( $this.closest('table').find('select option[value=' + $this.val() + ']:selected').length > 1) {
alert('option is already selected');
$this.val($this.find("option:first").val());
}
});
关于javascript - 避免使用 jquery 多次选择相同的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30570981/