[英]How to use selector to locate each child in a foreach loop in Jquery
I'm using Jquery and I want to use selector to locate each child in a foreach loop: 我正在使用Jquery,并且我想使用选择器在foreach循环中定位每个孩子:
$('div.parents').children('a').each(function(i) {
setTimeout(function(){
$(this).trigger( "click" );
},2000 + i * 2000);
});
However, $(this) seems not work at all. 但是, $(this)似乎根本不起作用。 The list looks like this: And if I change $(this).trigger( "click" );
该列表如下所示:如果我更改$(this).trigger(“ click”); to $('a').trigger( "click" );
到$('a')。trigger(“ click”); it will open all the links at once.
它将立即打开所有链接。
<div class="parents">
<a class="child"></a>
<a class="child"></a>
<a class="child"></a>
...
</div>
Thanks for your help! 谢谢你的帮助!
To let this
inside setTimeout
points to this
outside of setTimeout
, 要让
setTimeout
内部的this
指向setTimeout
外部的this
,
you can use jQuery's $.proxy
: 您可以使用jQuery的
$.proxy
:
$('div.parents').children('a').each(function(i) {
setTimeout($.proxy(function(){
$(this).trigger( "click" );
},this),2000 + i * 2000);
});
Or .bind
[works only in browsers compatible with ECMAScript 5 ]: 或
.bind
[仅在与ECMAScript 5兼容的浏览器中有效 ]:
$('div.parents').children('a').each(function(i) {
setTimeout(function(){
$(this).trigger( "click" );
}.bind(this),2000 + i * 2000);
});
The problem is this
inside the setTimeout callback does not point to the clicked element, you can use a closure variable to fix this issue 问题是
this
在setTimeout回调内部不指向clicked元素,您可以使用闭包变量来解决此问题
$('div.parents').children('a').each(function(i) {
var $this = $(this)
setTimeout(function(){
$this.trigger( "click" );
},2000 + i * 2000);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.