【问题标题】:Getting the value of a <tr> from a dynamic table, but I only get the value of the first <tr>从动态表中获取 <tr> 的值,但我只获取第一个 <tr> 的值
【发布时间】:2015-11-13 22:10:15
【问题描述】:

我试图在单击时获取一行的值,但即使我单击其他 tr,它也只会获取第一个 tr 的值。如何获取我点击的 tr 的值?

我用 jsonresponse 填满我的表。这是我的代码。

这是我的代码。

注册.html

<table class="table table-striped table-hover table-bordered" style="width:100%" border="0" id="miembrotb">

JsonResponse.js

$("#buscar_paciente").click(function(e) {
        var completo = $("#nombre").val();

        var input_string = completo;
        $.ajax({    
            url: "/datospacientejson",
            type: "POST",
            dataType: "json",
            data: {
                nombre: input_string,
                csrfmiddlewaretoken: '{{ csrf_token }}'
            },
             success: function (json) {
                var jsonResponse = eval(json);
                    $("#miembrotb").empty();
                    $("#miembrotb").append('<tr><th>ID</th><th>NOMBRE</th><th>FECHA DE NACIMIENTO</th></tr>');
                    $.each(jsonResponse, function (index, element) {
                        html = '<tr><td class="td1">'+jsonResponse[index]["fields"]["folio"]+'</td><td>'+jsonResponse[index]["fields"]["nombre"]+' '+jsonResponse[index]["fields"]["apellido_paterno"]+'<td>'+jsonResponse[index]["fields"]["fecha_nacimiento"]+'</td>'+'</tr>'
                        $("#miembrotb").append(html);
                    });
                },
            error: function(xhr, errmsg, err) {
                alert(xhr.status + "ERROR EN BUSQUEDA DE INFORMACION DEL PACIENTE: " + xhr.responseText);
            }
        });
        return false;
});



//ON CLICK FUNCTION
  $("#miembrotb").click(function(){//click anywhere in a row
    alert($(this).find("tr").html());
  });

【问题讨论】:

  • 你可以尝试以下更改 '$('.td1').click' 然后$(this).html() 这应该可以工作

标签: jquery html jsonresponse


【解决方案1】:

您需要将点击事件附加到ID为miembrotb的表格内的特定tr元素

$("#miembrotb tr").click(function(){//click anywhere in a row
       $(this).html();
  });

【讨论】:

    【解决方案2】:

    您正在做的是检查用户是否点击了整个表格,而不是特定的行。这样,您不知道单击了哪一行,因此无法从该行中获取信息。

    此外,当您执行$(this).find("tr") 时,您将获得一个包含填充查询的所有元素的数组,因此您将获得表中的每一行。

    您需要的是,向行添加一个类,然后使用以下代码将事件监听器添加到它们:

    $('.table-class').click(function(){
        $(this).html();
    });
    

    这样,您将从您单击的行中获取 html。此外,如果您正在动态创建它们,则可能需要在创建它们后附加事件侦听器。

    希望这会有所帮助。

    【讨论】:

    • 你能告诉我更多关于事件监听器的信息吗,因为你分享的代码不起作用,它会破坏表中的所有信息。
    • 您是否为所有表格添加了一个类?你也可以像$('#miembrotb tr).click'
    猜你喜欢
    • 1970-01-01
    • 2013-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多