2

我有一个在点击 TD 中的链接时调用的函数。单击后,我将 DOM 遍历到链接所在的 TR,然后在其后创建一个新的 TR。

到现在为止还挺好。

既然我已经创建了包含 TD 的新 TR,那么现在最好引用那个新创建的 TD。或者,我是否需要遍历从原始单击对象创建的新 TD?

$("td.expandable a").click(function(){
    // figure out the number of columns we need to span
    var colspan;
    colspan = $(this).parents("tr").children("td").size();

    // insert the new TR
    $(this).parents("tr").after("<tr><td colspan=' & colspan & '></td></tr>");

    // **what syntax would I use here to refer to the above made TD?**

    return false;
});
4

2 回答 2

1
$("td.expandable a").click(function(){
        // figure out the number of columns we need to span
        var colspan = $(this).parents("tr").children("td").size(),
            tr = $("<tr><td colspan=' & colspan & '></td></tr>");

        // insert the new TR
        $(this).parents("tr").after(tr);

        // **what syntax would I use here to refer to the above made TD?**
        tr.find('td')

        return false;
});

如果您要更新一个tr ,您也可以替换parents为。另一种更手动的方法是......closest$(this).parents('tr').next().find('td')

于 2009-10-22T23:53:24.990 回答
0

insertAfter().wrap() 对这种类型的事情很方便:

$('td.expandable a').click(function() {
    var $parent = $(this).parents('tr');
    var colCount = $parent.children('td').size();
    var $td = $('<td colspan=' + colCount + '></td>');
    $td.insertAfter($parent).wrap('<tr></tr>');
    return false;
});

我使用了字符串连接运算符“+”。“&”用于整数计算按位与。

于 2009-10-23T15:16:10.830 回答