简体   繁体   English

jQuery插件传入的设置范围

[英]jQuery plugin scope of settings passed in

I feel like this must have been asked, but I'm unable to find it through my searches. 我觉得必须要问这个问题,但是我无法通过搜索找到它。

Here's a complete example of the issue that's confusing me: 这是使我感到困惑的问题的完整示例:

<html><head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
(function($){
    $.fn.testPlugin = function(options){
    settings = $.extend({val : "default"}, options);
    return this.each(function(){
        $(this).click(function(e){ 
        e.preventDefault();
        console.log(settings.val);
        });
    });
    }
 })(jQuery);

$(document).ready(function(){
    $('a#a1').testPlugin();
    $('a#a2').testPlugin({val : 'new val'});

});
</script>
</head><body>
<a href="#" id="a1">A1</a>
<a href="#" id="a2">A2</a>
</body>
</html>

Clicking on either link will log "new val" to your firebug console. 单击任一链接将“ new val”登录到您的Firebug控制台。 You can probably imagine that I want the first link to keep the default settings, and the second to have my overwritten settings. 您可能会想到,我希望第一个链接保留默认设置,而第二个链接保留我的覆盖设置。 There must be a standard pattern for achieving this for a plugin? 必须为插件实现此标准的模式吗?

I think you need to use var to keep the settings variable in scope. 我认为您需要使用varsettings变量保留在范围内。 Try: 尝试:

 $.fn.testPlugin = function(options){
        var settings = $.extend({val : "default"}, options);
        return this.each(function(){
            $(this).click(function(e){ 
                e.preventDefault();
                console.log(settings.val);
            });
        });
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM