如何更改每次点击功能的{id}值

时间:2017-05-04 10:02:26

标签: javascript php jquery

这里我有一个代码,其中每个click函数的工作都会生成一个新行,每个行都有id值,并且从该id值我需要得到该行中另一列的结果。< / p>

$("#addrow").click(function () {
    $(".item-row:last").after('<tr class="item-row"><td class="description">' +
        '<select class="form-control select2" name="branch" id="branch_ids"">' +
        '<option value="">Choose Branch</option><?php foreach ($branch as $val) {?>' +
        '<option value="<?php echo $val->id; ?>"><?php echo $val->name; ?></option><?php } ?></select>' +
        '</td><td><textarea name="amount[]" id="amounts" class="cost textarea" required></textarea></td></tr>');

    $("#branch_ids").change(function () {
        var branch = $(this).val();
        var url = "<?php echo base_url();?>bills/get_corresponding_code";
        $.post(url, { branch: branch }, function (data) {
            $('#amounts').html(data);
        });
    });
});

此处只有第一行受到影响。

1 个答案:

答案 0 :(得分:1)

此处只有第一行受到影响。这是预期的行为,因为标识符必须是唯一的。

但是,您可以为它们分配一个CSS类,即 branch_ids Event Delegation,以使用Class Selector (".class")

绑定事件处理程序
$("#addrow").click(function() {
    $(".item-row:last").after('<tr class="item-row"><td class="description">' +
            '<select class="form-control select2 branch_ids" name="branch">' +
            '<option value="">Choose Branch</option><?php foreach ($branch as $val) {?>' +
            '<option value="<?php echo $val->id; ?>"><?php echo $val->name; ?></option><?php } ?></select>' +
            '</td><td><textarea name="amount[]" class="cost textarea amounts" required></textarea></td></tr>');
});

$(doument).on('change', '.branch_ids', function() {
    var branch = $(this).val();
    var amount = $(this).closest('item-row').find('.amounts');

    var url = "<?php echo base_url();?>bills/get_corresponding_code";
    $.post(url, {
        branch: branch
    }, function(data) {
        amount.html(data);
    });
});

注意:代替document,您应该使用最近的静态容器。