使用nth-child选择添加到DOM的元素时遇到问题

时间:2013-05-23 15:49:23

标签: jquery dom

我的应用程序允许用户向DOM添加/删除对象。 (单击要添加的形状,单击添加的形状以将其删除。)

这可以正常工作,但是现在我希望能够访问这些添加的形状并对其进行操作。

(尝试)循环通过nth-child

for(i=0; i<this.shape.length; i++) {
    $('#selected_shape_table:nth-child('+i+')').html("test"); 
}

HTML

<table id="selected_shape_table">

</table>

(最初向表格添加形状)

$('.shape').click(function() {
    var typeOfShape = $(this).attr('id');
    $('#selected_shape_table').append('<td><div id="' + typeOfShape + '" class=selected_shape"> + typeOfShape + '</div></td>'); 
});

1 个答案:

答案 0 :(得分:1)

#selected_shape_table:nth-child(2)选择第三个#selected_shape_table元素,这不是您尝试做的事情。

jQuery有.eq()方法:

$('#selected_shape_table *').eq(i).html('test');

此外,请确保使用事件委派或将事件侦听器代码放在循环之后。

相关问题