使用jquery根据第一个选项设置第二个选项的值

Set the second option value according to the first option using jquery

本文关键字:选项 设置 第二个 第一个 jquery 使用      更新时间:2023-09-26

我有一个表。我使用jquery动态地向表中添加行。每行有3个选择标记。我想将第三个选项的值设置为与第二个选项相同。

下面是我的代码:
$('#table tr').each(function () {
    $(this).find('select:eq(1)').change(function () {
        var selectedVal = $("#table").find('select:eq(1)').val();
        $('#table').find('select:eq(2)').val(selectedVal);
    });
});

但我的问题是它只工作一行。我的代码有什么问题?

JSFiddle

委托事件并使用作为选择器tr td:nth-child(2) select:

$('#table').on('change', 'tr td:nth-child(2) select', function () {
     $(this).closest('tr').find('select:eq(2)').val(this.value);
 });

-jsFiddle -

为动态事件使用事件委托

$('#table').on('change', 'tr select:nth-child(1)',function() {   
    //traverse to  the parent row
    var tr = $(this).closest('tr');
    //Find the second select
    var secondSelect = tr.find('select:eq(2)');
    //Set value
    secondSelect.val($(this).val());
});

首先:

var selectedVal = $("#table").find('select:eq(1)').val();

应该是:

var selectedVal = $(this).find('select:eq(1)').val();

否则你只得到第一行的select…

但是更好一点的可能是:

 $('#table tr').each(function(iter, elem) {                                     
     $(elem).find('select:eq(1)').change(function(){
         var selectedVal=$(this).val();
         $('#table').find('select:eq(2)').val(selectedVal);
    });
});