获取动态生成的Selectbox的数据属性



我有两个ajax请求后生成的选择框:

$("#job_id").change(function() {
    var id = $(this).val();
    $.ajax({
        url: '',
        type: 'POST',
        dataType: 'json',
        data: { 'id': id },
    }).done(function(data) {
        var contc = "";
        var contc2 = "N/A";
        var seal = "";
        var seal2 = "N/A";
        $.each(data, function(i, d) {
            contc += "" + d.container_no + "";
            contc2 += "" + d.container_no + "";
        });
        $("#container1").html(contc);
        $("#container2").html(contc2);
        // console.log("done"); 
    }).fail(function() {
        $("#container1").html("");
        $("#container2").html("");
    });
    $.ajax({
        url: '',
        type: 'POST',
        dataType: 'json',
        data: { 'id': id },
    }).done(function(d) {
        $("#cont_pickup").val(d.id);
        $("#cont_pickup_name").val(d.name);
    }).fail(function() {
        $("#cont_pickup").val("");
        $("#cont_pickup_name").val("");
    });
});

我想要data-seal值。为此我写了:

$("#container1,#container2").change(function() {
    $("#cont_seal_1").val($("#container1").data('seal'));
    $("#cont_seal_2").val($("#container2").data('seal'));
});

但是它返回undefined。如何获得data-seal

请尝试以这种方式:

$("#container1,#container2").change(function() {
    $("#cont_seal_1").val($("#container1 option:selected").data('seal'));
    $("#cont_seal_2").val($("#container2 option:selected").data('seal'));
});

您可以从select

获得selected optiondata-seal
$("#container1,#container2").change(function() {
    $("#cont_seal_1").val($("#container1 option:selected").data('seal'));
    $("#cont_seal_2").val($("#container2 option:selected").data('seal'));
});

$("#container1,#container2").change(function() {
    $("#cont_seal_1").val($("#container1 option:selected").attr('data-seal'));
    $("#cont_seal_2").val($("#container2 option:selected").attr('data-seal'));
});

如果您的项目是动态添加的,请尝试阅读有关jQuery on()live()

示例:

$( "#dataTable tbody" ).on( "click", "tr", function() {
 console.log( $( this ).text() );
});

最新更新