避免使用jquery多次选择相同的选项

Ros*_*ose 11 html javascript jquery

我有两个表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());
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

当在第一个表和第二个表中选择相同时,它将提醒已选择的选项.我的代码出了什么问题?

你可以在这里测试代码.

lsh*_*tyl 6

问题是您正在选择所有选项(table1 + 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());   
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

演示@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());
    }
});
Run Code Online (Sandbox Code Playgroud)