首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Jquery each in方法

问Jquery each in方法
EN

Stack Overflow用户
提问于 2012-07-20 16:46:11
回答 4查看 86关注 0票数 2

我有一个类播放列表:

代码语言:javascript
复制
function Playlist() {
    this.episodes = [ /*episode list*/ ];
};

我想做一个显示每一集的方法:

代码语言:javascript
复制
Playlist.prototype.display = function() {
    $('.episodeList').each(function(index) {
        $(this).children('title').text(this.episodes[index].title);
    });
}

问题是,在'.episodesindex‘之前的'this’表示所选的dom对象,而不是我的播放列表。

我该如何解决这个问题?谢谢。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-07-20 16:51:50

Javascript中的一种常见做法是创建一个新变量来存储当前类,因为this变量的内容会随着上下文的变化而变化。考虑一下像这样的事情

代码语言:javascript
复制
    function Playlist()
    {
        var self = this;
        this.episodes = [/*episode list*/];

        this.display = function()
        {
            $('.episodeList').each(function(index) {
                $(this).children('title').text(self.episodes[index].title);
            });
        }
    };

用于Playlist类定义,并调用myPlaylist.display()以显示内容。

票数 -2
EN

Stack Overflow用户

发布于 2012-07-20 16:52:36

将函数绑定到您的上下文:

代码语言:javascript
复制
$('.episodeList').each($.proxy(function(index, elem) {
    $(elem).children('title').text(this.episodes[index].title);
}, this));

有关jQuery.proxy的更多信息

票数 1
EN

Stack Overflow用户

发布于 2012-07-20 17:18:32

如果在dom元素上使用each,则每个元素内this都有对dom元素的引用

例如:

代码语言:javascript
复制
Playlist.prototype.display = function(e)
{                                       
    $('.episodeList').each(function(index) {                                  
            console.log(this)                                       
    });
}

console.log打印dom元素,并且它是正确的。现在将控制台日志放在每个日志之外,如下所示:

代码语言:javascript
复制
Playlist.prototype.display = function(e)
{   
    console.log(this)                            
    $('.episodeList').each(function(index) {                                  

    });
}

现在,console.log应该输出PlayList函数(您的类)。因此每个作用域中" this“都引用了dom元素,但是Playlist.prototype.display作用域中的this引用了播放列表函数。

解决方案是:

代码语言:javascript
复制
Playlist.prototype.display = function(e)
{   
    var self = this;                            
    $('.episodeList').each(function(index) {                                  
        console.log(self)
        console.log(this)                   
    });
}      

你需要把"this“从Playlist作用域和属性中带到self变量中,所以现在self已经引用了Playlist。现在你做了每个,所以当前的this在每个都有对dom元素的引用,但是self变量仍然有对Playlist的引用。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11575939

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档