each() inside function() and $(this)
each() inside function() and $(this)
假设这是我们的函数:
$('ul li').bind('click', function(){
$('iframe').each(function(){
// who is this???
alert(this);
});
});
可以看到,有一个。each()句子里面使用了$(this)
,
$(this)
将引用什么元素??ul li
吗?还是iframe
?我正在尝试,你可以猜到,选择每个iframe(在网页中,与ul无关,那里)
我问这个,因为我得到意想不到的结果与一个更大的函数,
this
指的是最具体的函数作用域的对象。
$('ul li').bind('click', function(){
// this = [ul li]
$('iframe').each(function(){
// this = [iframe]
});
});
如果你想从iframe
内部函数中引用this
的ul li
版本,你必须在它周围形成一个闭包,如下所示:
$('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());
});
警报输出:
0: foo
<1:酒吧/strong>
this
将引用iframe
对象。以上代码摘自jQuery文档。
你可能想告诉我们预期的结果是什么,也许在这里发布整个代码。
它指的是iframe,你可以从这里查看http://jsfiddle.net/x2XyU/1/
相关文章:
- How can I get and replace this in javascript ( jquery?
- Javascript Object - using jQuery and this
- Combine $(this) and $("li:eq(ui.item.index())")
- jQuery off() and bind(this)
- Accessing $(this).next and slideDown
- jQuery: addClass and click function for this class
- Javascript scope and self=this, _this=this, that=this
- javascript $(this).find and innerHTML
- IE 7 jquery bind and $(this)
- JavaScript - 'this' inside setTimeout and requestAni
- ExtJS and this.control query
- this.$el and jQuery
- Jquery $(this), .children, .siblings and etc
- 在javascript正则表达式中检查“this AND that WITHOUT this”的方法
- 验证的重点是错误,AND引用THIS元素
- Jquery - Using a function with .click and 'this'
- EE2 and zoom.js bigimage=$(this)
- each() inside function() and $(this)
- obj and $this returning undefined
- Javascript: this and onClick