each() inside function() and $(this)
Lets say this is o开发者_StackOverflowur function:
$('ul li').bind('click', function(){
$('iframe').each(function(){
// who is this???
alert(this);
});
});
As you can see, there is an .each() sentence that is using $(this)
inside,
What element will be referenced by $(this)
??? ul li
? or iframe
? I'm trying, as you can guess, to select each iframe (in the webpage, nothin to do with ul li, there)
I ask this because i am getting unexpected results with a way larger function,
this
refers to the object of the most specific function scope.
$('ul li').bind('click', function(){
// this = [ul li]
$('iframe').each(function(){
// this = [iframe]
});
});
If you want to reference the the ul li
version of this
from inside the iframe
inner function, you would have to form a closure around it, like the following:
$('ul li').bind('click', function () {
// cache this
var that = this;
$('iframe').each(function () {
// here, this = [iframe] and
// that = [ul li]
});
});
http://api.jquery.com/each/
HTML:
<ul>
<li>foo</li>
<li>bar</li>
</ul>
Javascript:
$('li').each(function(index) {
alert(index + ': ' + $(this).text());
});
Alert output:
0: foo
1: bar
this
will refer to the iframe
objects.
The above code is taken from the jQuery documentation.
You might want to tell us what the expected results, and maybe post the whole code here.
It refers to iframe u can check it from here http://jsfiddle.net/x2XyU/1/
精彩评论