[英]jquery: select element with classname and node index
I have a bunch of elements with the class ".myclass". 我有一堆带有“.myclass”类的元素。 Now I'd like to select one of these elements by its node index and animate it. 现在我想通过节点索引选择其中一个元素并为其设置动画。 I get an error that says the element has no function animate. 我收到一个错误,指出该元素没有函数动画。
example: 例:
<div class="myclass"></div>
<div class="myclass"></div>
<div class="myclass"></div>
var indizes = [0, 3];
$.each(indizes, function(i, v) {
$('.myclass')[v].animate({
left: 100
}, 1000);
});
Apparently the error comes from using a wrong selector. 显然,错误来自使用错误的选择器。 It does work if I use 如果我使用它确实有用
$($('.myclass')[v])
instead of 代替
$('.myclass')[v]
Is this the actual problem? 这是实际问题吗? It seems so weird to me to nest selectors. 嵌套选择器对我来说似乎很奇怪。
Is this the actual problem? 这是实际问题吗?
Yes. 是。 If you access a selected element via bracket notation, you get the raw DOM element back. 如果通过括号表示法访问所选元素,则会返回原始DOM元素。 DOM elements don't have an animate
method. DOM元素没有animate
方法。 By passing the DOM element to jQuery again ( $($('.myclass')[v])
) you are creating a jQuery object (again). 通过再次将DOM元素传递给jQuery( $($('.myclass')[v])
),您将再次创建一个jQuery对象。
You can avoid this and use .eq
to get a jQuery object for the element at that index: 您可以避免这种情况并使用.eq
来获取该索引处元素的jQuery对象:
$('.myclass').eq(v);
It would be better to keep a reference to the selected elements outside the loop though: 最好在循环外保留对所选元素的引用:
var indizes = [0, 3];
var $elements = $('.myclass');
$.each(indizes, function(i, v) {
$elements.eq(v).animate({
left: 100
}, 1000);
});
Alternatively, you can use .filter
to filter out the elements you want to animate, which at least looks a bit more concise: 或者,您可以使用.filter
过滤掉您想要制作动画的元素,这至少看起来更简洁:
$('.myclass').filter(function(i) {
return $.inArray(i, indizes) > -1;
}).animate({
left: 100
}, 1000);
You are doing everything right, and yes you do have to re-wrap the element like so. 你正在做的一切正确,是的,你必须像这样重新包装元素。
var indizes = [0, 3],
elements = $('.myclass');
$.each(indizes, function(i, v) {
$(elements[v]).animate({
left: 100
}, 1000);
});
When you do $('.myclass')[0]
then that element doesn't have any jQuery methods attached to it anymore 当你执行$('.myclass')[0]
,那个元素就不再有任何附加到它的jQuery方法了
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.