【问题标题】:How to get the variable's value from a plguin or send the value out from the plugin?如何从插件中获取变量的值或从插件中发送值?
【发布时间】:2011-12-31 11:46:14
【问题描述】:

如何从插件中获取变量的值或从插件中发送值?

例如,这是我的插件,它通过 ajax 检索用户信息并将用户信息存储在变量中,

(function($){

   $.fn.extend({ 

        get_authentication: function(options) {

            var defaults = {
                file:           'authentication_json.php',
                location:       'cms/'
            }

            var options = $.extend(defaults, options);

            var o = options;
            var object = $(this); // now the object is the selected element such as #popup

            $.get(http_root + rp_cms+ o.file, function(data){

                if(data) var user_id = data.user_id;

                // Redirect if the date returns as 'expired'.
                if(data && data.error == 'expired') window.location = http_root + o.location;
                //alert("Data Loaded: " + data);

            },"json");
        }
    });

 })(jQuery);

当我点击某个链接时,我会调用这个插件,

$('.get-user').click(function(){

   $.fn.get_authentication();
   alert(user_id);
});

我收到这样的错误。

有什么想法吗?

【问题讨论】:

标签: json jquery jquery-plugins


【解决方案1】:

我为您的插件添加了回调。这是一个示例 + 修改后的代码

(function($) {
    $.fn.extend({
        get_authentication: function(options) {
            var defaults = {
                file: 'authentication_json.php',
                location: 'cms/',
                callback: function(user_id) {}
            }
            var options = $.extend(defaults, options);

            var o = options;
            var object = $(this); // now the object is the selected element such as #popup
            $.get(http_root + rp_cms + o.file, function(data) {
                if (data)
                    options.callback(data.user_id);

                // Redirect if the date returns as 'expired'.
                if (data && data.error == 'expired') window.location = http_root + o.location;
                    alert("Data Loaded: " + data);
            }, "json");
        }
    });
})(jQuery);

$(function() {
    $.fn.get_authentication({
        callback: function(user_id) {
            alert(user_id);
        }
    });
});

【讨论】:

  • 非常感谢这个答案,曼努埃尔。 callback 是我今天刚从你那里学到的关于编写插件的新东西。谢谢! :-)
【解决方案2】:

编辑:

正如 Manuel 所说,使用回调。

【讨论】:

  • $.get 在请求完成时触发一个事件。在发生这种情况时,函数已经完成并且不会返回任何内容
猜你喜欢
  • 2017-10-22
  • 2016-02-01
  • 1970-01-01
  • 2014-11-09
  • 2013-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多