在$ .each里面的对象方法中使用"this"

Oli*_*i_M 0 javascript each jquery object

我试图this指向img对象方法中的每个函数内部,就像这样

var responsiveImageSwap = (function(){
    return {
        init : function(){
            $.each('img', function(){
                var width     = $(window).width(),
                    _this     = this, 
                    alert(_this.attr('src'))
            })
        }
    }
})();
responsiveImageSwap.init();
Run Code Online (Sandbox Code Playgroud)

但它是引用object而不是img,我如何引用图像?

Roc*_*mat 8

$.each用于循环集合.你正在做的是循环字符串中的字母'img'.

你想用.each; 这是针对jQuery对象的.

$('img').each(function(){
    var width = $(window).width(),
        // this is a DOM element, we need to make it a jQuery object
        _this = $(this), 
     alert(_this.attr('src'))
});
Run Code Online (Sandbox Code Playgroud)