gpt4 book ai didi

jquery - 我的第一个 jQuery 插件,函数和全局变量去了哪里?

转载 作者:行者123 更新时间:2023-12-03 22:39:51 24 4
gpt4 key购买 nike

我正在编写我的第一个 jQuery 插件,我有一些关于应该把东西放在哪里的问题。我尝试四处搜索,但似乎有不同的方法来构建插件,所以我迷路了。我通过关注 jQuery 网站上的创作插件文档走到了这一步,但不确定下一步该去哪里。

  1. 公共(public)函数应该放在哪里?以 hello() 为例。假设我计划在整个插件中使用该功能,它应该位于哪里?现在我把它放在顶部,这似乎有效,但我不确定这是正确的做法。

  2. 在哪里放置全局变量?以我的变量“imgs”数组为例。我应该在我现在拥有的地方、在我的 init 方法中还是在其他地方声明它?

    (function($){

    function hello(){
    alert("hello world");
    }
    var imgs = new Array();

    var methods = {
    init: function(options){
    if(options){
    $.extend({
    width: 200,
    height: 200,
    selectedColor: '#123456'
    }, options);

    // for every image do something
    this.find('img').each(function(){
    var $this = $(this);

    var width = $this.width();
    var height = $this.height();

    console.log("width: " + width + " height: " + height);

    selection = function() {
    console.log($this.attr('src'));
    hello();
    };

    $this.bind('click', selection);
    });
    }
    return this;
    },
    test : function( string ) {
    console.log("Test: " + string);
    //return "here";
    }
    };


    $.fn.Thumbnails = function(method) {
    // Method calling logic
    if ( methods[method] ) {
    return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
    return methods.init.apply( this, arguments );
    } else {
    $.error( 'Method ' + method + ' does not exist on jQuery.Thumbnails' );
    }

    };

    })(jQuery);

    $thumbnails = $('#imagescontainer').Thumbnails({
    height: 150,
    });

感谢您的帮助!

最佳答案

  1. 将它们放在 jQuery 函数之外,但在自执行函数内。这将确保它们仅存在于您的 jQuery 函数中。例如,您可以看到实用程序函数 findText() 位于我的插件 bumpyText 中的 jQuery 函数之外。 .

  2. 这取决于其所需的生命周期。如果每次调用函数时都需要它,请将其放在函数中。如果它应该在每次插件调用时保留其状态(不太可能),请将其放在 jQuery 函数之外。

关于jquery - 我的第一个 jQuery 插件,函数和全局变量去了哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5656868/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com