jquery prev()返回undef

时间:2015-06-30 16:51:37

标签: javascript jquery html

通过JSON接收数据并在表上添加内容后,使用事件委托来捕获此内容的链接,但是当您单击动态创建的链接时想要访问prev()包含的tr元素data-id。但这是我回归undef。有人能帮我吗? prev()由editarComercial()

调用

使用Javascript:

$(document).ready(function(){

    function editarComercial(trthis) {
        alert($(trthis).prev().prev().data('id'));
    }

    function listaComercial(){

        url = BASE_URL + 'comercial/ajaxrequest/listagem';

        $.getJSON(url,function(data){

            var trs = [];
            $.each(data,function (key){

                tr = "<tr data-id=\""+data[key].id+"\">";
                tr += "<td>"+data[key].nome+"</td>";
                tr += "<td><a href=\"javascript:void(0);\" class=\"edit-comercial\">Editar</a>";
                tr += "<a href=\"javascript:void(0);\" class=\"del-comercial\">Excluir</a></td>";
                tr += "</tr>";

               trs.push(tr);
            });
            $("<tbody/>",{
                html: trs.join("")
            }).appendTo("#listagemComercial");
        });

    }

    $(document).on('click','a.edit-comercial',function(){
        editarComercial(this);
    });

    listaComercial();
 });

HTML:

    <div id="content">
    <table id="listagemComercial">
        <thead>
            <tr>
                <th>Nome</th>
                <th>Ações</th>
            </tr>
        </thead>
    </table>
</div>

1 个答案:

答案 0 :(得分:3)

.edit-comercial没有前一个元素,它是TD中的第一个元素。

您可能需要closest()来遍历行

function editarComercial(trthis) {
    alert( $(trthis).closest('tr').data('id') );
}
相关问题