使用“;这个“;internal$.each内部对象方法

use "this" inside $.each inside object method

本文关键字:内部对象 方法 each internal 这个 使用      更新时间:2023-09-26

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

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

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

$.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'))
});

这个?

return {
    init: function () {
        var vw = $(window).width(); // viewport width
        $('img').each(function () {
            var $img = $(this);
            // Do stuff with $img, e.g. retrieve $img.attr('src')
        });
    }
};