【问题标题】:jQuery collections, function and organisationjQuery 集合、功能和组织
【发布时间】:2013-08-22 15:04:38
【问题描述】:

我有以下代码,它采用单个图像并对其应用特定宽度:

function Foo ( img ) {
    this.image = img;
}
Foo.prototype._getWidth = function( ) {
    return this.image.data('largest') + 'px';
};
Foo.prototype.applyWidth = function(  ) {
    this.image.css( 'width', this._getWidth() );
};

var img = Foo( $('img') );

img.applyWidth();

但是,我正在努力处理 jQuery 图像集合,例如没有 for 循环的 $('img') 或每个函数内部的 $.each()(我有超过上面显示的这两个函数)。

到目前为止,我想出的最好的是:

var temp = [];

function Create ( imgs ) {
    $.each( imgs, function( i ){
        temp[ i ] = new Foo ( $( this ) );
    });
    return temp;
}

Create( $('img') );

$.each( temp, function() {
    $(this).applyWidth();
}):

这很好用,但感觉没有条理,感觉马虎。

最后,我想要一些关于以下方面的指导。

  1. 理想情况下,我希望它位于命名空间 Theme 下。我想使用模块模式在Theme.Images 下使用这种方法。这可能吗?

  2. 1234563 _getWidth() 的唯一值。目前我认为我需要循环 Theme.Images.temp 并在循环内调用 applyWidth()

我真的开始欣赏 javascript 中的继承这一点,并希望继续使用它。

【问题讨论】:

    标签: javascript jquery object


    【解决方案1】:
    var Theme = (function(){
    
        function Theme(images) {
            var _this = this;
            this.images = [];
            images.each(function(){
               _this.images.push(new Image(this))
            });
        }
    
        var Image = (function(){
    
            function Image(imageDOM) {
                this.image = $(imageDOM);
            }
            Image.prototype._getWidth = function( ) {
                return this.image.data('largest') + 'px';
            };
            Image.prototype.applyWidth = function(  ) {
                this.image.css( 'width', this._getWidth() );
            };
    
            return Image;
    
        })();
    
        Theme.prototype.applyWidth = function(){
            this.images.forEach(function(el){
                el.applyWidth();
            });
        }
    
    
        return Theme;
    
    })();
    

    那么你可以这样做:

    var MyTheme = new Theme($(some_selector));
    MyTheme.applyWidth();
    

    【讨论】:

    • 感谢您的明确回答,很好地清除了我的模糊理解。
    • 没问题。很高兴帮助@mikedidthis ^_^
    【解决方案2】:

    在我看来,您正在寻找“收藏”类。

    function Images() {
        var that = this;
        that.foos = [];
        $('img').each(function() {
            that.foos.push(new Foo(this));
        });
    }
    
    Images.prototype.applyWidth = function() {
        $.each(this.foos, function() {
            this.applyWidth();
        });
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-02
      • 2021-12-29
      • 1970-01-01
      • 2017-10-04
      相关资源
      最近更新 更多