开发者

Most succint way to refer to a newly created object in jQuery?

开发者 https://www.devze.com 2022-12-09 11:26 出处:网络
I have a function called on the click of a link within a TD. Upon clicking, I traverse back up the DOM to the TR that the link was within, then create a new TR after it.

I have a function called on the click of a link within a TD. Upon clicking, I traverse back up the DOM to the TR that the link was within, then create a new TR after it.

So far so good.

Now that I've created that new TR, with a TD within, what's the best to now refer to that newly created TD. Or, do I need to traverse my way b开发者_StackOverflow社区ack into the new TD I created back from the original clicked object?

$("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;
});


$("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;
});

You can also probably substitute parents with closest if you're updating one tr. An alternative yet more manual way would have been to do... $(this).parents('tr').next().find('td')


insertAfter().wrap() are convenient for this type of thing:

$('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;
});

I used the string concatentation operator "+". "&" is used for integers to calculate bitwise AND.

0

精彩评论

暂无评论...
验证码 换一张
取 消