jQuery-使用'eq()'作为选择器动态创建的元素
问题描述:
我有一些图像,并且我使用jQuery将每个图像包装在<li>
中.然后,我想通过索引选择这些列表元素之一.
I've got some images and I've used jQuery to wrap each image in a <li>
. I then want to select one of these list elements by index.
HTML
<div id="slider">
<img src="..." alt="" />
<img src="..." alt="" />
<img src="..." alt="" />
</div>
jQuery
$('#slider').children().wrap('<li />');
$('#slider').wrapInner('<ul class="sliderUl" />');
var sliderLi = $('#slider').find('li');
$(sliderLi + ':eq(2)').addClass('test');
这不起作用,因为list元素是动态创建的,因此尽管该变量似乎已创建并且可以正常使用,但不适用于'eq'.有什么想法我还能做什么?
This doesn't work because the list elements are created dynamically, so although the variable seems to be created and work ok, it doesn't work with the 'eq'. Any ideas what else I can do?
我必须使用列表元素作为变量.
I have to do it using the list elements as a variable.
答
您尝试使用eq()
,就像:eq
slideLi是对象而非选择器一样.
You are try to use eq()
like :eq
sliderLi is object not selector.
更改
$(sliderLi + 'eq(2)').addClass('test');
收件人
$(sliderLi).eq(2).addClass('test');
OR,使用:eq
$('#slider').find('li:eq(2)').addClass('test');