global or local variables in a jquery-plugin

前端 未结 2 1772
耶瑟儿~
耶瑟儿~ 2021-02-04 18:02

How is it possible to give a jquery-plugin individual local variables, that are accessable in different plugin-functions?

My script shows an alert with the content \'123

2条回答
  •  孤城傲影
    2021-02-04 18:41

    The usual way to do this is to use the data function to store your information related to a specific element on the element itself. So in your case (live example):

    (function ($) {
        $.fn.doSomething = function()
        {
            alert(this.data("myHtmlControl"));
        }
        $.fn.myHtmlControl = function(option) {
            this.data("myHtmlControl", option);
        }
    })(jQuery);
    

    If you need to store multiple options, here's a more robust example (live copy):

    (function ($) {
        var defaults = {
            msg1: "(msg1)",
            msg2: "(msg2)"
        };
    
        $.fn.doSomething1 = function()
        {
            alert(getOption(this, "msg1"));
            return this;
        }
        $.fn.doSomething2 = function()
        {
            alert(getOption(this, "msg2"));
            return this;
        }
    
        $.fn.myHtmlControl = function(options) {
            this.data("myHtmlControl", $.extend({}, defaults, options));
            return this;
        };
    
        function getOption(inst, name) {
            var obj = inst.data("myHtmlControl");
            return (obj || defaults)[name];
        }
    
        function setOption(inst, name, value) {
            var obj = inst.data("myHtmlControl");
            if (!obj) {
                obj = $.extend({}, defaults);
                inst.data("myHtmlControl", obj);
            }
            obj[name] = value;
        }
    })(jQuery);
    jQuery(function($) {
    
        $("#theButton").click(function() {
            $('#ctrl1').myHtmlControl({msg1: "abc"});
            $('#ctrl2').myHtmlControl({msg2: "123"});
            alert("about to do ctrl1");
            $('#ctrl1').doSomething1().doSomething2();
            alert("about to do ctrl2");
            $('#ctrl2').doSomething1().doSomething2();
        });
    
    });
    

提交回复
热议问题