2009-10-22 72 views
2

我有一个函数调用TD中的链接点击。点击后,我将DOM返回到链接所在的TR,然后创建一个新的TR。大多数方法来引用jQuery中新创建的对象?

到目前为止这么好。

现在我已经创建了新的TR,其中有TD,现在最好指的是新创建的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; 
}); 

回答

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; 
}); 

您也可以或许替代parentsclosest如果您要更新一个 TR。 。另一种还更手动的方式将是做... $(this).parents('tr').next().find('td')

+0

不会tr.find('td')批处理新创建的TR的所有实例吗?在我的情况下,我们可能会插入一堆这些,只想匹配我刚创建的那个。 我可能会误解'父母'。是否将该对象的父TR或全部父TR作为数组返回?如果是后者,我认为我需要最接近的。 – 2009-10-23 00:01:01

+0

啊,确实......我需要使用'最接近'而不是'父母',因为我只有一个单亲。 另外,在第二次阅读时,我现在意识到'tr'不是一个字符串,而是一个实际的jquery对象,因此确实会匹配那个特定的对象。谢谢你! – 2009-10-23 00:04:17

0

insertAfter()包()是方便这种类型的事情:

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

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

相关问题