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

标签 javascript jquery html

我有两个表 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/

相关文章:

javascript - 在js中捕获自定义异常

javascript - Array.push() 与对象

javascript - 为什么 jQuery slideToggle() 函数在我的表中表现异常?

javascript - 在 Codepen 元素中使用 fullpage.js 时遇到问题

javascript - 使用回调时的 express.js 请求/响应对象生命周期

javascript - $.load(content) 之后在 jQuery 中无法访问元素

JQuery Accordion 菜单在加载时闪烁

javascript - 检测到多个事件,其中应该只有一个

html - 表格数据宽度不适用

javascript - ListView 没有滚动条