每个方法中都有Jquery

时间:2012-07-20 08:46:11

标签: javascript jquery methods this each

我有一个播放列表:

function Playlist() {
    this.episodes = [ /*episode list*/ ];
};

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

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

问题是'.episodes [index]'之前的'this'代表所选的dom对象,而不是我的播放列表。

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

4 个答案:

答案 0 :(得分:1)

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

$('.episodeList').each($.proxy(function(index, elem) {
    $(elem).children('title').text(this.episodes[index].title);
}, this));

更多关于jQuery.proxy

答案 1 :(得分:0)

如果您对dom元素使用each,则每个this都会引用dom元素

例如:

Playlist.prototype.display = function(e)
{                                       
    $('.episodeList').each(function(index) {                                  
            console.log(this)                                       
    });
}

console.log打印dom元素,它是正确的。 现在把控制台日志放在各自之外:

Playlist.prototype.display = function(e)
{   
    console.log(this)                            
    $('.episodeList').each(function(index) {                                  

    });
}

现在console.log应该打印播放列表功能(你的班级)。所以每个范围中的“this”都引用了dom元素,但Playlist.prototype.display范围内的这个引用了播放列表函数。

解决方案是:

Playlist.prototype.display = function(e)
{   
    var self = this;                            
    $('.episodeList').each(function(index) {                                  
        console.log(self)
        console.log(this)                   
    });
}      

你需要从播放列表范围和属性中取“this”到self var,所以现在自己重新获得播放列表。现在你做了每一个,所以当前每个都引用了dom元素但是自变量仍然引用了播放列表。

答案 2 :(得分:-1)

在您的代码$(this)=episodes[index]中,因为它位于each函数中。我想这就是你想要的,

Playlist.prototype.display = function() {
  var element=$(this);

  $('.episodeList').each(function(index,item) {
        item.children('title').text(element.episodes[index].title);
    });
}

答案 3 :(得分:-2)

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

这样的东西
    function Playlist()
    {
        var self = this;
        this.episodes = [/*episode list*/];

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

您的播放列表类定义,并调用myPlaylist.display() 显示内容。